Commit 7cb62627 authored by christian.foerster's avatar christian.foerster
Browse files

minor changes

parent 73d053b5
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# A short Introdcution to Python # A short Introdcution to Python
## Things you might be wondering: ## Things you might be wondering:
- What is an Anaconda and what does it have to do with Python - What is an Anaconda and what does it have to do with Python
- Anaconda program to manage virtual environments - Anaconda program to manage virtual environments
- can be set up in a virtual environment - can be set up in a virtual environment
- Python 2 vs Python 3? - Python 2 vs Python 3?
- unsupported vs. supported - unsupported vs. supported
- Where does Python fit in? - Where does Python fit in?
- for educational purposes (https://www.researchgate.net/publication/328175547_MatLab_vs_Python_vs_R) - for educational purposes (https://www.researchgate.net/publication/328175547_MatLab_vs_Python_vs_R)
- more generally speaking (https://pyzo.org/python_vs_matlab.html) (R is mainly for data wrangling) - more generally speaking (https://pyzo.org/python_vs_matlab.html) (R is mainly for data wrangling)
- development -> if you want to develop open source software, that many people can use, you need a open source language! - development -> if you want to develop open source software, that many people can use, you need a open source language!
- Is Python fast? - Is Python fast?
- not really - not really
- it can comparable to c++/c/fortran (numpy, cython, numba) - it can comparable to c++/c/fortran (numpy, cython, numba)
- Why is Python so popular? - Why is Python so popular?
- easy to learn/use - easy to learn/use
- code readabiltiy - code readabiltiy
- open source - open source
- huge commuinuty - huge commuinuty
- general purpose language - general purpose language
## Some nice-to-know's ## Some nice-to-know's
* indexing starts at 0 * indexing starts at 0
* the syntax i controlled mainly by tabs (4 spaces), that mean less brackets and better readability * the syntax i controlled mainly by tabs (4 spaces), that mean less brackets and better readability
* so you should adapt your texteditor (e.g.: notepad++) to replace a tab with 4 spaces * so you should adapt your texteditor (e.g.: notepad++) to replace a tab with 4 spaces
* commet with hashtag, multiline comments/docstrings like so """my comment or docstring""" * commet with hashtag, multiline comments/docstrings like so """my comment or docstring"""
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Variables and Conversions ## Variables and Conversions
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Integer # Integer
a=25 a=25
# Float # Float
b=5.6 b=5.6
# String # String
c="6.7" c="6.7"
#Boolean #Boolean
d=True d=True
# Variable conversion work as follows. (int() always rounds down) # Variable conversion work as follows. (int() always rounds down)
print(float(a),float(c),int(b),str(b),sep="\n") print(float(a),float(c),int(b),str(b),sep="\n")
print("Some string") print("Some string")
a a
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
**Mind the difference between \/ and \/\/** **Mind the difference between \/ and \/\/**
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
**String formatting** **String formatting**
For quick and simple formatting For quick and simple formatting
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Float and int formatting in strings # Float and int formatting in strings
print("Ich bin %.2f alt." %29.324232) # % für hier muss noch was rein, .2 für 2 Kommastellen, f für float print("Ich bin %.2f alt." %29.324232) # % für hier muss noch was rein, .2 für 2 Kommastellen, f für float
print("Ich bin %i alt."%29) # ... print("Ich bin %i alt."%29) # ...
# concat strings # concat strings
print("Ich bin "+str(29)+" alt.") print("Ich bin "+str(29)+" alt.")
# copy pasting folder paths (use the r"" -> raw string mode) # copy pasting folder paths (use the r"" -> raw string mode)
print(r"C:\adg\ggj") print(r"C:\adg\ggj")
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
For complexer formatting For complexer formatting
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# straight forward without index the format arguments # straight forward without index the format arguments
print('{}, {}, {}'.format('a', 'b', 'c')) print('{}, {}, {}'.format('a', 'b', 'c'))
# indexing the format arguments # indexing the format arguments
print('first-{0},second-{1},third-{2}'.format('a', 'b', 'c')) print('first-{0},second-{1},third-{2}'.format('a', 'b', 'c'))
print('{2}, {1}, {0}'.format('a', 'b', 'c',"d")) print('{2}, {1}, {0}'.format('a', 'b', 'c',"d"))
print('{2}, {1}, {0}'.format(*'abcd')) # * unpacks the string into a tuple print('{2}, {1}, {0}'.format(*'abcd')) # * unpacks the string into a tuple
print('{0}+++{1}---{0}'.format('first', 'second')) print('{0}+++{1}---{0}'.format('first', 'second'))
# using keyword arguments and indexing in one step # using keyword arguments and indexing in one step
print("{x}-{x}={z[0]}".format(x=4,z=[0,7])) print("{x}-{x}={z[0]}".format(x=4,z=[0,7]))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# interesting string methods # interesting string methods
print("dd".replace("d","e")) print("dd".replace("d","e"))
print("edf.ggg".split(".")) print("edf.ggg".split("."))
print("55".isdigit()) print("55".isdigit())
# ... # ...
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# multiline string # multiline string
""" """
this is one this is one
... ...
""" """
# and this # and this
''' '''
also also
one one
''' '''
``` ```
%% Output %% Output
'\nalso \none\n' '\nalso \none\n'
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# keep in mind # keep in mind
''=="" ''==""
``` ```
%% Output %% Output
True True
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Basic Math Hints ## Basic Math Hints
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
#Attention! #Attention!
print("That's a: ", type(6/3)) print("That's a: ", type(6/3))
print("And that's a ",type(6//3)) print("And that's a ",type(6//3))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
8^5 # what the hell (https://stackoverflow.com/questions/2451386/what-does-the-caret-operator-in-python-do) 8^5 # what the hell (https://stackoverflow.com/questions/2451386/what-does-the-caret-operator-in-python-do)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(0^0,1^1,1^0,0^1, sep="\n") print(0^0,1^1,1^0,0^1, sep="\n")
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
8**5 # to the power of 8**5 # to the power of
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
-7 // 2 # integer division rounding down! -7 // 2 # integer division rounding down!
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
13 % 4 # modulo (divison remainder) 13 % 4 # modulo (divison remainder)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
x = 3 x = 3
x += 3 # same as x = x + 3 x += 3 # same as x = x + 3
x *= 2 # same as x = x * 2 x *= 2 # same as x = x * 2
x /= 4 # same as x = x / 4 x /= 4 # same as x = x / 4
x x
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Basic Data Structures ## Basic Data Structures
- list() -> ordered, mutable structure (indexing via number) - list() -> ordered, mutable structure (indexing via number)
- dict() -> unordered structure (indexing via keyword) - dict() -> unordered structure (indexing via keyword)
- tuple() -> ordered, immutable structure (indexing via number) - tuple() -> ordered, immutable structure (indexing via number)
- sets() -> unordered,immutable representation with unique values only (does not support indexing) - sets() -> unordered,immutable representation with unique values only (does not support indexing)
### Lists ### Lists
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# initiate an empty list # initiate an empty list
mylist=[] # or list() mylist=[] # or list()
print(mylist) print(mylist)
# adding values to a list one at a time # adding values to a list one at a time
mylist.append(2) mylist.append(2)
mylist.append(4) mylist.append(4)
print(mylist) print(mylist)
# joining lists, adding mutiple values at once # joining lists, adding mutiple values at once
mylist.extend([22,14]) mylist.extend([22,14])
mylist=mylist+[25,43] mylist=mylist+[25,43]
mylist+=[235,143] mylist+=[235,143]
print(mylist) print(mylist)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Indexing, slicing, reversing lists Indexing, slicing, reversing lists
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
Numbers=[1,2,3,4,5,6,7,8,9,10] Numbers=[1,2,3,4,5,6,7,8,9,10]
# slice # slice
print(Numbers[2:5]) print(Numbers[2:5])
print(Numbers[:5]) print(Numbers[:5])
# index # index
print(Numbers[0]) # gibt den letzten Wert aus print(Numbers[0]) # gibt den letzten Wert aus
# reverse # reverse
print(Numbers[::-1]) print(Numbers[::-1])
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# sort # sort
Numbers.sort() Numbers.sort()
print(Numbers) print(Numbers)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
What can we store in a list? What can we store in a list?
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# lists, dictionary and tuple are very versatile and can store all possible data structures and other things # lists, dictionary and tuple are very versatile and can store all possible data structures and other things
newlist=[2,3.2,[3],True] newlist=[2,3.2,[3],True]
# print the type of the stored values # print the type of the stored values
print(type(newlist[0]),type(newlist[1]),type(newlist[2]),sep="\n") print(type(newlist[0]),type(newlist[1]),type(newlist[2]),sep="\n")
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# string to list # string to list
list("abcdefghijklmnopqrstuvwxyz") list("abcdefghijklmnopqrstuvwxyz")
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Attention: pointer or new list?! Attention: pointer or new list?!
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a=[4,5,6] a=[4,5,6]
b=a b=a
b[0]=99 b[0]=99
b.append(5) b.append(5)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a a
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
id(a)==id(b) id(a)==id(b)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
c=a.copy()# copy list (also a[:]) c=a.copy()# copy list (also a[:])
c[2]=9999 c[2]=9999
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a a
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
id(a)==id(c) id(a)==id(c)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Tupel ### Tuple
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# tuple are intitated with tuple() or () # tuple are intitated with tuple() or ()
x = (1, 2, 3) x = (1, 2, 3)
len(x) len(x)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# indexing, slicing and reversing is the same as in lists # indexing, slicing and reversing is the same as in lists
y = (4, 5, 6) y = (4, 5, 6)
print(y[:2]) print(y[:2])
print(y[-1]) print(y[-1])
y[::-1] y[::-1]
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
listOfTuples = [x, y] listOfTuples = [x, y]
listOfTuples listOfTuples
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
**Unpacking of lists and tuples** **Unpacking of lists and tuples**
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
(age, income) = "32,120000".split(',') (age, income) = "32,120000".split(',')
print(age) print(age)
print(income) print(income)
print(income.replace("0","9")) print(income.replace("0","9"))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Dictionaries ### Dictionaries
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# initiate a dictionary {} or dict() # initiate a dictionary {} or dict()
lastnames = {} lastnames = {}
# fill the dictionary # fill the dictionary
lastnames["Jakob"] = "Benisch" lastnames["Jakob"] = "Benisch"
lastnames["Stefanie"] = "Wiek" lastnames["Stefanie"] = "Wiek"
lastnames["Winnie"] = "Puh" lastnames["Winnie"] = "Puh"
lastnames["Christian"] = "Koch" lastnames["Christian"] = "Koch"
lastnames["blaa"]=[1,2,3,43,12,21,3,43] lastnames["blaa"]=[1,2,3,43,12,21,3,43]
print(lastnames) print(lastnames)
# indexing # indexing
print(lastnames["Christian"]) print(lastnames["Christian"])
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# indexing with error catch # indexing with error catch
print(lastnames.get("Bruno")) print(lastnames.get("Bruno"))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# accessing data of a dict # accessing data of a dict
print(lastnames.items()) print(lastnames.items())
print(lastnames.keys()) print(lastnames.keys())
print(lastnames.values()) print(lastnames.values())
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Some problematic as in lists pointers and new dictionary # Some problematic as in lists pointers and new dictionary
a={"a":3} a={"a":3}
b=a.copy() b=a.copy()
b["a"]=99 b["a"]=99
a a
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Sets ### Sets
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a={1,2,3,4,3,4,5} a={1,2,3,4,3,4,5}
print("a: {}".format(a)) print("a: {}".format(a))
b=set([2,4,2,2,6,4,23]) b=set([2,4,2,2,6,4,23])
print("b: {}".format(b)) print("b: {}".format(b))
print("In a but not in b: {}".format(a.difference(b))) print("In a but not in b: {}".format(a.difference(b)))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
**A quick Comparison** **A quick Comparison**
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# list # list
[1,2,3,4,5,3] [1,2,3,4,5,3]
# tuple # tuple
(3,2,4) (3,2,4)
# dict # dict
{"myname":40} {"myname":40}
# set # set
{1,2,3} {1,2,3}
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# For all of these we can use the in statement to check whether a number is in a given list. # For all of these we can use the in statement to check whether a number is in a given list.
3 in [3,4] 3 in [3,4]
3 in {3:"for dictionaries the key will be checked"} 3 in {3:"for dictionaries the key will be checked"}
3 in (3,4) 3 in (3,4)
3 in {3,4} 3 in {3,4}
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Learning by doing! ## Learning by doing!
In order to not fall asleep when looking at python syntax, let's have a little break and do some exercises. In order to not fall asleep when looking at python syntax, let's have a little break and do some exercises.
### Exercise Round 1 ### Exercise Round 1
- What's the remainder of $2^{99}$ divided by $57$? - What's the remainder of $2^{99}$ divided by $57$?
- If you were to write a little database, that gets one file for every day containing data for that day. - If you were to write a little database, that gets one file for every day containing data for that day.
And you want to store the file locations in a basic python data structure. Which one would you use and why? And you want to store the file locations in a basic python data structure. Which one would you use and why?
- If you want to check two large python lists for commen values, how would you do it? - If you want to check two large python lists for commen values, how would you do it?
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Loops ## Loops
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# summing up the values of a list # summing up the values of a list
summe=0 summe=0
for num in [1,2,3,4]: for num in [1,2,3,4]:
# everything that is endeted is within the loop # everything that is endeted is within the loop
summe+=num summe+=num
print(num) print(num)
print("Summe: "+str(summe)) print("Summe: "+str(summe))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
for number in [1,2,3,4,[],"ffffdd"]: for number in [1,2,3,4,[],"ffffdd"]:
print(number) print(number)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# while loop example # while loop example
start=1 start=1
end=6 end=6
while start<end: while start<end:
print(start) print(start)
start+=1 start+=1
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# be careful with while loop # be careful with while loop
# this one would run endlessly # this one would run endlessly
#while True: #while True:
# a=1 # a=1
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# nested loop matrix (m,n) filled with ones, technically speaking its a list not a matrix... # nested loop matrix (m,n) filled with ones, technically speaking its a list not a matrix...
m=4 m=4
n=10 n=10
matrix=[] matrix=[]
for i_m in range(m): for i_m in range(m):
matrix.append([]) matrix.append([])
for i_n in range(n): for i_n in range(n):
matrix[i_m].append("{},{}".format(i_m,i_n)) matrix[i_m].append("{},{}".format(i_m,i_n))
matrix matrix
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Control Statements ## Control Statements
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a=2 a=2
if a==3: if a==3:
print("a is 3!") print("a is 3!")
elif a==1: elif a==1:
print("a is 1!") print("a is 1!")
else: else:
print("a is not 3, nor 1!") print("a is not 3, nor 1!")
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# try rerunning that script # try rerunning that script
if type(age)==str: if type(age)==str:
print("Told you its a string!") print("Told you its a string!")
# converts to an integer # converts to an integer
age=int(age) age=int(age)
else: else:
print("Guess I was wrong. It's a %s" %str(type(age))) print("Guess I was wrong. It's a %s" %str(type(age)))
#converts to a string #converts to a string
age=str(age) age=str(age)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Nifty One-Liners ## Nifty One-Liners
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# control statement one - liner # control statement one - liner
3 if 3==3 else "bollox" 3 if 3==3 else "bollox"
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# fancy list comprehension -> even or uneven? # fancy list comprehension -> even or uneven?
[(True,i) if i%2==0 else (False,i) for i in range(29)] [(True,i) if i%2==0 else (False,i) for i in range(29)]
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# dictionary comprehension # dictionary comprehension
{key: value for key, value in zip(["a","b","c"],[1,2,3])} {key: value for key, value in zip(["a","b","c"],[1,2,3])}
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Exercise Round 2 ### Exercise Round 2
Lets write a little program which can be used to analyse files and can count the occurance of patterns in each line! Lets write a little program which can be used to analyse files and can count the occurance of patterns in each line!
__Pattern Analyser__ __Pattern Analyser__
Input: Input:
- A string! (later a file) - A string! (later a file)
Output: Output:
- Number of occurances in each line! - Number of occurances in each line!
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Standard Functions ## Standard Functions
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
help(abs) help(abs)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
min([1,2]) min([1,2])
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
max([1,2]) max([1,2])
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
sorted([8,1,2]) sorted([8,1,2])
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
len([1,2]) len([1,2])
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
range(99) range(99)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
zip([2,3,4],[55,77,66]) zip([2,3,4],[55,77,66])
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
enumerate([3,4,5]) enumerate([3,4,5])
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
sum([3,4,67]) sum([3,4,67])
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
all([True,True]) and not any([False, False]) all([True,True]) and not any([False, False])
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Writing your own Functions ## Writing your own Functions
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# function to add two arguments # function to add two arguments
def sum_1(a,b): def sum_1(a,b):
return a+b return a+b
# funtion with provided default values for arguments # funtion with provided default values for arguments
def sum_2(a,b=6,c=9,d=98): def sum_2(a,b=6,c=9,d=98):
''' '''
this is my docstring this is my docstring
''' '''
c=a+b+c c=a+b+c
return c return c
# this function does add the two input arguments but does not return them # this function does add the two input arguments but does not return them
def sum_3(a,b): def sum_3(a,b):
c=a+b c=a+b
return 3,4,5 return 3,4,5
# playing around with the defined functions # playing around with the defined functions
print(sum_1(2,3)) print(sum_1(2,3))
print(sum_2(2,c=-44)) print(sum_2(2,c=-44))
print(sum_3(2,3)) print(sum_3(2,3))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# you can even pass functions as function arguments
def add_ten(func,a,b):
'''
my function
'''
return func(a,b)+10
print(add_ten(sum_2,0,1))
```
%% Cell type:code id: tags:
``` python
import sys
sys.getrecursionlimit()
#sys.setrecursionlimit()
```
%% Cell type:code id: tags:
``` python
# recursion works like this (std limit 3000) # recursion works like this (std limit 3000)
def factorial_slow(n): def factorial_slow(n):
if n==1: if n==1:
return n return n
else: else:
return n*factorial(n-1) return n*factorial_slow(n-1)
# lets compare the execution time of recursion to a while loop # lets compare the execution time of recursion to a while loop
def factorial_fast(m): def factorial_fast(m):
res=1 res=1
while m>1: while m>1:
res*=m res*=m
m-=1 m-=1
return res return res
def factorial_fastest(number): def factorial_fastest(number):
if number == 1 or number == 0: if number == 1 or number == 0:
return 1 return 1
result = 1 # variable to hold the result result = 1 # variable to hold the result
for x in range(1, number + 1, 1): for x in range(1, number + 1, 1):
result *= x result *= x
return result return result
# performance check # performance check
%timeit factorial_slow(2000) %timeit factorial_slow(2000)
%timeit factorial_fast(2000) %timeit factorial_fast(2000)
%timeit factorial_fastest(2000) %timeit factorial_fastest(2000)
# for is faster than while # for is faster than while
``` ```
%% Output
1.54 ms ± 69.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1.02 ms ± 23.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
842 µs ± 22 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%% Cell type:code id: tags:
``` python
# you can even pass functions as function arguments
def add_ten(func,a,b):
'''
my function
'''
return func(a,b)+10
print(add_ten(sum_2,0,1))
```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# decorators # decorators
def pretty_print(func): def pretty_print(func):
def wrap(arg): def wrap(arg):
symbols="-"*len(arg) symbols="-"*len(arg)
print(symbols) print(symbols)
res=func(arg) res=func(arg)
print(symbols) print(symbols)
return res return res
return wrap return wrap
@pretty_print @pretty_print
def printer(string=3): def printer(string=3):
print(string) print(string)
printer(" o -|- ofdsgafdgfdsagdsgsa ") printer(" o -|- ofdsgafdgfdsagdsgsa ")
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# special function argumentes # special function argumentes
def arbitiary_number_of_arguments(*args): def arbitiary_number_of_arguments(*args):
print(*args) print(*args)
print(args) print(args)
return "-".join([str(a) for a in args]) return "-".join([str(a) for a in args])
arbitiary_number_of_arguments(2,3,4,5,6) arbitiary_number_of_arguments(2,3,4,5,6)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# special function keyargumentes # special function keyargumentes
def arbitiary_number_of_keyword_arguments(**kwargs): def arbitiary_number_of_keyword_arguments(**kwargs):
print(kwargs) print(kwargs)
arbitiary_number_of_keyword_arguments(ab=2,cd=4,ef=5,gh="ee") arbitiary_number_of_keyword_arguments(ab=2,cd=4,ef=5,gh="ee")
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# args before kwargs!! # args before kwargs!!
def both(*args,**kwargs): def both(*args,**kwargs):
return args,kwargs return args,kwargs
both(3,4,2,4,5,wa=2,ab=44) both(3,4,2,4,5,wa=2,ab=44)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Generators ## Generators
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# define a generator with the yield statement # define a generator with the yield statement
def squared_range(n): def squared_range(n):
for i in range(n): for i in range(n):
yield i**2 yield i**2
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# using a generator in a loop # using a generator in a loop
for val in squared_range(8): for val in squared_range(8):
print(val) print(val)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
gen=squared_range(8) gen=squared_range(8)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# use with the next statement # use with the next statement
next(gen) next(gen)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Local vs Global Variables ## Local vs Global Variables
Variables can have a local or a global scope. For instance variables used in a function are only known within that function -> local. Variables can have a local or a global scope. For instance variables used in a function are only known within that function -> local.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# defining a global variable # defining a global variable
i_glob=2 i_glob=2
# a function defined to change the value of i_glob # a function defined to change the value of i_glob
def changeVariable(): def changeVariable():
i_glob = 33 i_glob = 33
return return
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# which number will be printed???? # which number will be printed????
changeVariable() changeVariable()
#print(i_glob) #print(i_glob)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
i_glob=2 i_glob=2
# changing global variables from within a function # changing global variables from within a function
def changeVariable(): def changeVariable():
global i_glob global i_glob
i_glob = 222 i_glob = 222
return return
changeVariable() changeVariable()
#print(i_glob) #print(i_glob)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# other ways to access local and global variables # other ways to access local and global variables
def test(): def test():
a = 9 a = 9
b = 99 b = 99
c = 999 c = 999
print(locals()) print(locals())
test() test()
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
globals() globals()
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(a_local) print(a_local)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def update_globals_with_locals(): def update_globals_with_locals():
a_local="how convenient" a_local="how convenient"
globals().update(locals()) globals().update(locals())
return return
update_globals_with_locals() update_globals_with_locals()
print(a_local) print(a_local)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Import Packages ## Import Packages
Like in moste programming languages many packages exist... To install packages you can use *pip* (Package Installer Python). If you have anaconda installed you can also use *conda*. Like in moste programming languages many packages exist... To install packages you can use *pip* (Package Installer Python). If you have anaconda installed you can also use *conda*.
Open a terminal/console and install packages like so: Open a terminal/console and install packages like so:
**pip install _packagename_** or **conda install _packagename_** **pip install _packagename_** or **conda install _packagename_**
Once the desired package is installed you can import it. Once the desired package is installed you can import it.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# import the package numpy # import the package numpy
import numpy import numpy
# import the package numpy to a variable called np # import the package numpy to a variable called np
import numpy as np import numpy as np
# import the function "array" from the package numpy # import the function "array" from the package numpy
from numpy import array from numpy import array
# import all functions from the package numpy # import all functions from the package numpy
from numpy import * from numpy import *
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Depending on how you import packages the access to it's functions is slightly different. Depending on how you import packages the access to it's functions is slightly different.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# create a list # create a list
Liste=[1,2,3] Liste=[1,2,3]
# import numpy # import numpy
import numpy import numpy
# convert list to numpy array # convert list to numpy array
Array=numpy.array(Liste) Array=numpy.array(Liste)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# import numpy to variable np # import numpy to variable np
import numpy as np import numpy as np
# convert list to numpy array # convert list to numpy array
Array=np.array(Liste) Array=np.array(Liste)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# import only the array funtion from the package numpy # import only the array funtion from the package numpy
from numpy import array from numpy import array
# convert list to numpy array # convert list to numpy array
Array=array(Liste) Array=array(Liste)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Working with Files (low level) ## Working with Files (low level)
**opening modes:** **opening modes:**
'r' open for reading (default) 'r' open for reading (default)
'w' open for writing, truncating the file first 'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists 'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists 'a' open for writing, appending to the end of the file if it exists
'b' binary mode 'b' binary mode
't' text mode (default) 't' text mode (default)
'+' open for updating (reading and writing) '+' open for updating (reading and writing)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# read a file line by line # read a file line by line
myFile=open("data/data_file.txt","r") myFile=open("data/data_file.txt","r")
for line in myFile: for line in myFile:
print(line) print(line)
myFile.close() myFile.close()
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# keepting the data # keepting the data
file_list=[] file_list=[]
file=open("data/data_file.txt","r") file=open("data/data_file.txt","r")
for line in file: for line in file:
file_list.append(line) file_list.append(line)
file.close() file.close()
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# another way (the cleanest, as the file is closed automatically) # another way (the cleanest, as the file is closed automatically)
with open("data/data_file.txt") as f: with open("data/data_file.txt") as f:
read_data = f.read() read_data = f.read()
read_data read_data
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# writing new file plus creating it (line by line writing) # writing new file plus creating it (line by line writing)
file=open("data/data_file_new.txt","w+") file=open("data/data_file_new.txt","w+")
for line in file_list: for line in file_list:
file.write(line) file.write(line)
file.close() file.close()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Exercise Round 3 ### Exercise Round 3
Adapt our previous analyser to read a file and analyse it! Adapt our previous analyser to read a file and analyse it!
__Pattern Analyser__ __Pattern Analyser__
Input: Input:
- A file - A file
Output: Output:
- A dict containg the line numbers as keys and occurances in that line as value! - A dict containg the line numbers as keys and occurances in that line as value!
Lines without occurances should not be in the dictionary. Lines without occurances should not be in the dictionary.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Object Oriented Programming ## Object Oriented Programming
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## 4 Pillars of OOP ## 4 Pillars of OOP
- Inheritance (a way to reuse your code) - Inheritance (a way to reuse your code)
- Abstraction (showing only essential features hiding details) - Abstraction (showing only essential features hiding details)
- Encapsulation (bind data variables and functions together in a class) - Encapsulation (bind data variables and functions together in a class)
- Polymorphism (create functions with same name and different arguments, redefine functions) - Polymorphism (create functions with same name and different arguments, redefine functions)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Parent class # Parent class
class Dog: class Dog:
# Class attribute # Class attribute
species = 'mammal' species = 'mammal'
# Initializer / Instance attributes # Initializer / Instance attributes
def __init__(self, name, age): def __init__(self, name, age):
self.name = name self.name = name
self.age = age self.age = age
# instance method # instance method
def description(self): def description(self):
return "{} is {} years old".format(self.name, self.age) return "{} is {} years old".format(self.name, self.age)
# instance method # instance method
def speak(self, sound): def speak(self, sound):
return "{} says {}".format(self.name, sound) return "{} says {}".format(self.name, sound)
# Child class (inherits from Dog() class) # Child class (inherits from Dog() class)
class RussellTerrier(Dog): class RussellTerrier(Dog):
def run(self, speed): def run(self, speed):
return "{} runs {}".format(self.name, speed) return "{} runs {}".format(self.name, speed)
# Child class (inherits from Dog() class) # Child class (inherits from Dog() class)
class Bulldog(Dog): class Bulldog(Dog):
def run(self, speed): def run(self, speed):
return "{} runs {}".format(self.name, speed) return "{} runs {}".format(self.name, speed)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Child classes inherit attributes and # Child classes inherit attributes and
# behaviors from the parent class # behaviors from the parent class
jim = Bulldog("Jim", 12) jim = Bulldog("Jim", 12)
print(jim.description()) print(jim.description())
# Child classes have specific attributes # Child classes have specific attributes
# and behaviors as well # and behaviors as well
print(jim.run("slowly")) print(jim.run("slowly"))
# Is jim an instance of Dog()? # Is jim an instance of Dog()?
print(isinstance(jim, Dog)) print(isinstance(jim, Dog))
# Is julie an instance of Dog()? # Is julie an instance of Dog()?
julie = Dog("Julie", 100) julie = Dog("Julie", 100)
print(isinstance(julie, Dog)) print(isinstance(julie, Dog))
# Is johnny walker an instance of Bulldog() # Is johnny walker an instance of Bulldog()
johnnywalker = RussellTerrier("Johnny Walker", 4) johnnywalker = RussellTerrier("Johnny Walker", 4)
print(isinstance(johnnywalker, Bulldog)) print(isinstance(johnnywalker, Bulldog))
# Is julie and instance of jim? # Is julie and instance of jim?
print(isinstance(julie, RussellTerrier)) print(isinstance(julie, RussellTerrier))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Special Methods, hidden Variables, ... ## Special Methods, hidden Variables, ...
Fancy things we can do! Fancy things we can do!
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
class Bank_Account(): class Bank_Account():
bank = "Some Bank" bank = "Some Bank"
'''my documentation''' '''my documentation'''
# this function is being run, when the class is initialized. # this function is being run, when the class is initialized.
# (So when an object is created) # (So when an object is created)
def __init__(self, account_balance): def __init__(self, account_balance):
self.balance = account_balance self.balance = account_balance
return return
# this is a method - a function belonging to a class # this is a method - a function belonging to a class
def withdraw(self, amount): def withdraw(self, amount):
'''more documentation''' '''more documentation'''
self.balance -= amount self.balance -= amount
return return
# this is a method - a function belonging to a class # this is a method - a function belonging to a class
def deposit(self, amount): def deposit(self, amount):
self.balance += amount self.balance += amount
return return
# this is a protected method # this is a protected method
def _protected(self): def _protected(self):
print("easy to access...") print("easy to access...")
# this is a hidden method # this is a hidden method
def __hidden(self): def __hidden(self):
print("can't make python methods more private than this...") print("can't make python methods more private than this...")
# this is a so called magix method, just like __init__ # this is a so called magix method, just like __init__
def __add__(self, other): def __add__(self, other):
balanceSum = self.balance + other.balance balanceSum = self.balance + other.balance
print("Their future shared account holds {}.".format(balanceSum)) print("Their future shared account holds {}.".format(balanceSum))
return self.balance + other.balance return self.balance + other.balance
# the representation of the instance # the representation of the instance
def __repr__(self): def __repr__(self):
return "This is an instance of the class {}.".format(self.__class__.__name__) return "This is an instance of the class {}.".format(self.__class__.__name__)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# create objects (objects are instnances of a class) # create objects (objects are instnances of a class)
Jana=Bank_Account(33) Jana=Bank_Account(33)
Steffen=Bank_Account(644) Steffen=Bank_Account(644)
Jana.withdraw(10) Jana.withdraw(10)
Jana+Steffen Jana+Steffen
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
If you want to know more about OOP check out: https://www.oodesign.com/ If you want to know more about OOP check out: https://www.oodesign.com/
## Error Handling ## Error Handling
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# cause an error # cause an error
"e"+3 "e"+3
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# catch the error # catch the error
try: try:
"e"+3 "e"+3
except: except:
print("Caught it!") print("Caught it!")
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# better would be to catch a certain error # better would be to catch a certain error
# so that if something unexpected happens you will know what it is # so that if something unexpected happens you will know what it is
try: try:
"e"+3 "e"+3
except : except :
print(3) print(3)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Beispiele ## Beispiele
So jetzt zeigen ich einfach mal ein paar Beispiele und die kannst du ja mal nachvollziehen. Danach bekommst du ein paar Übungsaufgaben. So jetzt zeigen ich einfach mal ein paar Beispiele und die kannst du ja mal nachvollziehen. Danach bekommst du ein paar Übungsaufgaben.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
class Notepad(): class Notepad():
def __init__(self): def __init__(self):
self.notes = {} self.notes = {}
self.selectedNote=None self.selectedNote=None
return return
def _noteNameCheck(self,noteName): def _noteNameCheck(self,noteName):
if noteName is None and self.selectedNote is None: if noteName is None and self.selectedNote is None:
raise ValueError("Please provide a noteName.") raise ValueError("Please provide a noteName.")
elif noteName is None: elif noteName is None:
noteName = self.selectedNote noteName = self.selectedNote
return noteName return noteName
def addNote(self, noteName): def addNote(self, noteName):
self.selectedNote=noteName self.selectedNote=noteName
self.notes[noteName] = {} self.notes[noteName] = {}
return self.notes return self.notes
def deleteNote(self, noteName=None): def deleteNote(self, noteName=None):
noteName = self._noteNameCheck(noteName) noteName = self._noteNameCheck(noteName)
del self.notes[noteName] del self.notes[noteName]
self.selectedNote = None self.selectedNote = None
return self.notes return self.notes
def addEntry(self, entry, noteName=None): def addEntry(self, entry, noteName=None):
noteName = self._noteNameCheck(noteName) noteName = self._noteNameCheck(noteName)
self.notes[noteName][entry]="unmarked" self.notes[noteName][entry]="unmarked"
return self.notes return self.notes
def deleteEntry(self, entry, noteName=None): def deleteEntry(self, entry, noteName=None):
noteName = self._noteNameCheck(noteName) noteName = self._noteNameCheck(noteName)
del self.notes[noteName][entry] del self.notes[noteName][entry]
return self.notes return self.notes
def markEntry(self, entry, noteName=None): def markEntry(self, entry, noteName=None):
noteName = self._noteNameCheck(noteName) noteName = self._noteNameCheck(noteName)
self.notes[noteName][entry]="marked" self.notes[noteName][entry]="marked"
return self.notes return self.notes
NotepadInstance = Notepad() NotepadInstance = Notepad()
NotepadInstance.addNote("Shopping") NotepadInstance.addNote("Shopping")
NotepadInstance.addEntry("coffee") NotepadInstance.addEntry("coffee")
NotepadInstance.addEntry("milk") NotepadInstance.addEntry("milk")
NotepadInstance.addEntry("break") NotepadInstance.addEntry("break")
NotepadInstance.addEntry("chocolate") NotepadInstance.addEntry("chocolate")
NotepadInstance.markEntry("chocolate") NotepadInstance.markEntry("chocolate")
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# create your own error message # create your own error message
class WhatHaveYouDoneNowError(Exception): class WhatHaveYouDoneNowError(Exception):
pass pass
raise WhatHaveYouDoneNowError("This error occurs when you do things that fall under the category:'You have done what???????'") raise WhatHaveYouDoneNowError("This error occurs when you do things that fall under the category:'You have done what???????'")
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# list containing numbers from 1 to 10 # list containing numbers from 1 to 10
Numbers=list(range(11))[1:] Numbers=list(range(11))[1:]
# create a new list containing only even numbers # create a new list containing only even numbers
Even=[] Even=[]
for num in Numbers: for num in Numbers:
if num%2==0: if num%2==0:
Even.append(num) Even.append(num)
print(Even) print(Even)
# the short version with list comprehension # the short version with list comprehension
# mind the syntax, reads almost like a sentences # mind the syntax, reads almost like a sentences
Even=[num for num in Numbers if num%2==0] Even=[num for num in Numbers if num%2==0]
print(Even) print(Even)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# webscraping for a wg easy # webscraping for a wg easy
# popular package for sending HTTP requests # popular package for sending HTTP requests
import requests import requests
# regular expressions # regular expressions
import re import re
# get source of webpage # get source of webpage
r = requests.get("https://www.wgzimmer.ch/en/wgzimmer/search/mate/ch/zurich-stadt.html?wc_language=en") r = requests.get("https://www.wgzimmer.ch/en/wgzimmer/search/mate/ch/zurich-stadt.html?wc_language=en")
webpage_content = r.text webpage_content = r.text
# filtet to find links to flats # filtet to find links to flats
re.findall('''<a href="/en/wgzimmer/search/mate/ch/zurich-stadt/(.+).html">''',webpage_content) re.findall('''<a href="/en/wgzimmer/search/mate/ch/zurich-stadt/(.+).html">''',webpage_content)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# we'll create function that gets rid of repeating entries in lists # we'll create function that gets rid of repeating entries in lists
Liste=[1]*10+[2,2]+[3]*4 Liste=[1]*10+[2,2]+[3]*4
print(Liste) print(Liste)
def Uniquify_long(L): def Uniquify_long(L):
unique=[] unique=[]
for i in L: for i in L:
if i not in unique: if i not in unique:
unique.append(i) unique.append(i)
return unique return unique
print("Result of the long syntax: "+str(Uniquify_long(Liste))) print("Result of the long syntax: "+str(Uniquify_long(Liste)))
# or with list comprehension # or with list comprehension
def Uniquify_medium(L): def Uniquify_medium(L):
unique=[] unique=[]
[unique.append(i) for i in L if i not in unique] [unique.append(i) for i in L if i not in unique]
return unique return unique
print("Result of the medium syntax: "+str(Uniquify_medium(Liste))) print("Result of the medium syntax: "+str(Uniquify_medium(Liste)))
# and the shortest # and the shortest
def Uniquify_short(L): def Uniquify_short(L):
return [num for pos,num in enumerate(L) if num not in L[:pos]] return [num for pos,num in enumerate(L) if num not in L[:pos]]
print("Result of the short syntax: "+str(Uniquify_short(Liste))) print("Result of the short syntax: "+str(Uniquify_short(Liste)))
# thats the most efficient and easiest way # thats the most efficient and easiest way
print(set(Liste)) print(set(Liste))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# boolean expressions # boolean expressions
print(1 is not 3) print(1 is not 3)
print(True or False) print(True or False)
print(True==1) print(True==1)
print(False and False == False) print(False and False == False)
print((False and False) == False) print((False and False) == False)
``` ```
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment