Pyton for beginners
Zawartość:
Organizacja
- Ocena będzie wystawiana na podstawie ilości punktów z zaliczonych zadań.
- Zadania można oddawać na każdych zajęciach, wystarczy zademonstrować działanie programu oraz króciutko o nim opowiedzieć.
- Ćwiczenia z zestawu przypadającego na dane zajęcia można oddawać do
końca semestru ale …
- … jeżeli pod koniec semestru braknie czasu na zajęciach aby zadanie oddać to nie zostanie ono zalicone. W związku z tym proszę nie zwlekać z oddawaniem zadań.
- Skala ocen za punkty z zadań pojawi się około 10 tygodnia
- Na ostatnich zajęciach przeprowadzony jest egzamin, zagadnienia do zostaną rozesłane kilka tygodni wcześniej
- Ocena końcowa jest średnią ważoną oceny z zadań oraz egzaminu TODO
Materiały dodatkowe
- some tutorials available online:
- exercises in python
- some interesting books, also available online:
- miscellaneous
- installing things
- see Appendix A of Automate the Boring Stuff with Python
- files and folders
- see chapter 10 of Automate the Boring Stuff with Python
- copying things
- paths, relative paths, etc.
- platform independent paths
- date and time
- “Never ever deal with time zones if you can help it.”
- see chapter 17 of Automate the Boring Stuff with Python
- geeks for geeks article
- manipulating images
- see chapter 19 of Automate the Boring Stuff with Python
- opencv
- spreadsheets
- see chapter 13 of Automate the Boring Stuff with Python
- running external programs from python, capturing output
- installing things
Zestawy zadań
Set 1
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:
- You prepared a container of pre-boiled water cooled down to the temperature \(T_{\text{cool}}\).
- You prepared an empty, sterile feeding bottle.
- 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\)).
- 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 Vcoolthat 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.
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.
Write a python script that asks the user to input the arguments of
calculateVcool from A, runs the function
and prints the result.
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 :-) ).
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 Twhere 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:
- a list comprehension,
- tuple unpacking,
- the functions and .
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
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?
Set 2
Implement a function that takes an arbitrary number of arguments, say floating point numbers, and returns a dictionary containing:
- a list containing all the arguments
- the mean of the arguments
- the standard deviation of the arguments
Use this function in a script.
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.
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:
- use two nested
forloops to sweep over all the \(80 \times 40\) “pixel” display we use in the game - use
ifand / or a dictionary to decide what character to put in each “pixel” - the new line character is
\n - this does not have to be very complicated, drawing a map with the location of the player is great but printing some basic information about the game statistics is also fine
Implement a “smart” function:
def smartFunction(a , b):
# ...
return cthat 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?
Implement the function:
def readState(path)
# ...
return statethat 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 :-)
- simple
guessing game
- this is the example from class
- please have a look at the comments, in particluar they contain additiona information about reading and writing files
- game
of life
- see this Wikipedia article for more details
- run the game as usual
python ConowayGameOfLife.py- first press
cto change the state of chosen cells - next press
ito iterate - finally press
qto quit
- first press
- there are many comments
Set 3
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.
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.
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.
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?