Pyton for beginners

Zawartość:

Organizacja

OCENA

Materiały dodatkowe

Zestawy zadań

Set 1

…functions, numbers, tuples, and lists…
A
(3 points)

It’s \(3\) o’clock in the morning and you need to prepare some formula to feed your newborn baby. The instructions on the package are very specific: prepare a certain amount of water at a given temperature, add the correct amount of formula, mix and cool everything down before serving. In order to keep the baby safe from infections, all the water that you use needs to be pre-boiled. Here is your setup:

  1. You prepared a container of pre-boiled water cooled down to the temperature \(T_{\text{cool}}\).
  2. You prepared an empty, sterile feeding bottle.
  3. You have an electric kettle and measured that when the water comes out of the spout it has temperature \(T_{\text{hot}}\) (it’s slightly cooler then \(100^{\circ}C\)).
  4. You need to prepare \(V\) milliliters (or any other unit of volume) water at temperature \(T\) to mix up the formula for your little one. You do this by first pouring \(V_{\text{cool}}\) milliliters (or any other unit of volume) of the cooler water into the bottle and then filling the bottle up to \(V\) with the hot water from the kettle. How much cool water should you use?

The mathematics of this problem is very simple, see the APPENDIX. To make things more convenient implement the python function:

def calculateVcool(Tcool , Thot , V , T):
    #...
    return Vcool

that returns the volume of the cooler water \(V_{\text{cool}}\) you need to pour into the bottle before pouring the remainder of the water from the kettle. This volume is calculated in such a way that when mixed the water has temperature \(T\).

Tip: If you find yourself in this scenario a infrared thermometer is a fantastic tool.

B
(1 points)

Turn the V, T, and Thot arguments of function calculateVcool from exercise A into optional arguments with realistic default values for a \(3\) month old baby.

C
(2 points)

Write a python script that asks the user to input the arguments of calculateVcool from A, runs the function and prints the result.

D
(1 points)

Nobody has time to fiddle around with their laptop at \(3\) o’clock in the morning. Get the script from C to run on your phone (at your own risk :-) ).

E
(4 points)

Your significant other (SO) has the early morning shift with the baby and asked you to prepare a thermos with pre-boiled water. You have determined the temperature coefficient of the thermos (the mathematics of this is very simple, see the APPENDIX) and need to decide on the temperature of the water in the thermos so that in a couple of hours, when your SO needs to prepare the formula, the temperature of the water in the thermos is appropriate.

To help with this implement the python function:

def calculateTemperature(Tfinal , time , Troom , k , 
        search = (0.0 , 100.0 , 1000)):
    #...
    return T

where Tfinal is the desired temperature of the water after time time, Troom is the ambient room temperature and k is the temperature coefficient. The final optional argument search determines the parameters of a numerical simulation that will solve the problem. The returned value T is the desired temperature of water in the thermos.

Use a simple numerical simulation to solve the problem. In this simulation scan initial water temperature candidates in the range search[0] \(\ldots\) search[1]. The range is divided into search[2] temperature values. For each temperature candidate, the final temperature after time time is calculated (see APPENDIX). Finally, out of all the temperature candidates, the one whose final temperature is closest to the desired Tfinal is returned as T. In your implementation please use:

Tip: The exponent is available in the math library. There is no need to install anything, it comes built in. Simply use from math import exp

APPENDIX

When mixing water to arrive at a given temperature, approximately (the notation is the same as in the exercises): \[ V_{\text{cool}} = V \frac{T_{\text{hot}} - T}{T_{\text{hot}} - T_{\text{cool}}} \] Does it matter if we use \(^{\circ}C\) or \(^{\circ}K\)? Is the formula any different if you prefer to pour the hot water first?

When water in a container is left in a room with ambient temperature \(T_{\text{room}}\) it will gradually, over time change it’s temperature to match the ambient temperature. This process can be approximately modeled by the formula: \[ \tau(t) = T_{\text{room}} - (T_{\text{room}} - \tau(0)) e^{-t/k} \] where \(\tau(0)\) is the initial temperature of water in the thermos and \(\tau(t)\) is the temperature in the thermos after time \(t\). The remaining notation is the same as in the exercises. Please note that a non-standard definition of the temperature coefficient \(k\) is used. The value of this coefficient can be worked out by measuring the temperature of the water in the thermos at two points in time and doing a little algebra. Does it matter if we use \(^{\circ}C\) or \(^{\circ}K\)? Is the formula any different if you prefer to pour the hot water first?

ADDITONAL MATERIALS

Set 2

…to is or not to is, dictionaries, loops, flow control, modules and objects…
A
(2 points)

Implement a function that takes an arbitrary number of arguments, say floating point numbers, and returns a dictionary containing:

Use this function in a script.

B
(3 points)

Implement a simple text based game. The gameplay and objective is completely up to you.

Please base your implementation on the following function:

def updateGameState(state)
    # ...

that updates the dictionary state in every iteration of the main game loop:

while(!state["finished"]):
    # ...    

At each iteration of the game loop print the available moves / options available to the player and use the input function to decide on how to proceed with the game play. Use if, else, and elif statements to decide how the game state will evolve. When the game is finished, change the value of "finished" in state to True. This will cause the main loop of the game to terminate.

C
(3 points)

Add some elegant ASCI art to your game. To do this please import the sys module and use the sys.stdout.write method to implement the function:

def showGameState(state):
    # ...

that will print a beautiful graphical representation of the game state to “standard output”. Add this function to the main game loop. Please assume that we are working in a terminal that is \(80\) characters wide and \(40\) characters tall.

Tips:

D
(2 points)

Implement a “smart” function:

def smartFunction(a , b):
    # ...
    return c

that returns the result c = a + b. Since this operation is very laborious and time consuming, the function memorizes previous arguments a, b that were passed to it, it also memorizes the result. This is all in the hope that when we pass those arguments to the function again it won’t have to do all that work, it’ll just recall the result.

In order to achieve this introduce a global variable smartFunctionMemory that will contain a dictionary. The keys in this dictionary are related to the arguments a, b, and the values are related to the results c.

What types of arguments can we pass into smartFunction?

E
(2 points)

Implement the function:

def readState(path)
    # ...
    return state

that reads the state from a file located at path path. The contents of this file is processed to obtain the saved state of a previous game.

Implement the function:

def writeState(state , path)
    # ...

that writes the game state to a file located at path path.

Add readState before the start of the game loop and writeState after the loop to allow the user to save the game progress.

Tip: Don’t worry we’ll discuss the details during class :-)

ADDITONAL MATERIALS

Set 3

…literate programming, loops and lambdas, …
A
(2 points)

Replace the repeated if, elif, else statements from your game in Set 2 with match. If these statements don’t appear in the game, please add some.

B
(2 points)

End your scripts from Set 1 with an infinite while loop instead of a call similar to input("Hit enter to exit."). Please use pass in the infinite loop.

Import the time module and use the time.time() function to measure the time the program spends in the loop. If this time exceeds \(10\) seconds, ask the user if the program should exit. If the program is supposed to wait reset the timer and run the loop for another \(10\) seconds.

Tip: use continue, and break.

C
(4 points)

Using the Jupyter notebook please investigate the logistic map.

Create a function that calculates the logistic map and draw the map using the matplotlib library, we will discuss how this library works during class. Make sure the notebook has a detailed description of your approach, use literate programming.

D
(2 points)

Re-implement the function from C to accept a keyword argument drawFunction. If the value of this keyword argument is not the default None then drawFunction points to a function that draws the data and a plot of the logistic map is produced automatically.

Test if this works using a lambda expression.

Can you use is to check if drawFunction has the default value?