python 5 - lsis · write a python script to generate and print a dictionary that ... write a python...
TRANSCRIPT
Python 5Dictionaries, Functions, numpy
1
Goals (today)
• Dictionaries and tuples
• Functions: principles, definitions, argument passage
• numpy: presentation, useful functions
• Exercises
2
Project (2)
• Check the project on my page (Teachings / NEW! Big Data: Introduction to python (EN) / Projects)
3
Dictionaries
• Very practical for complex data structures
• Non ordered object collections
• Key-value pairs
4
Dictionaries>>>ani1={}
>>>ani1['name']='giraffe'
>>>ani1['height']=5.0
>>>ani1['weight']=1100
>>>ani1
{'name':'giraffe','height':5.0,'weight':1100}
>>>ani1['height']
5.0
5
keys() and values()>>>ani1.keys()
['name','height','weight']
>>>ani1.values()
['giraffe',5.0,1000]
• We can initialise the object in a single line instruction
>>> ani2 = {'name':'monkey', 'height':1.75,'weight':70}
6
List of dictionaries>>>animals=[ani1,ani2]
>>>animals
[{'name': 'giraffe', 'weight': 1100, 'height': 5.0},{'name':'monkey','weight':70,'height':1.75}]
>>>foraniinanimals:
...printani['name']
...
giraffe
monkey
7
Key existence>>>ifani2.has_key('weight'):
...print"Thekey'weight'existsforani2"
...
Thekey'weight'existsforani2
>>>if"weight"inani2:
...print"Thekey'weight'existsforani2"
...
Thekey'weight'existsforani2
8
Tuples• Like lists, but they cannot be modified
>>>x=(1,2,3)
>>>x
(1,2,3)
>>>x[2]
3
>>>x[0:2]
(1,2)
>>>x[2]=15
Traceback(innermostlast):
File"<stdin>",line1,in?
TypeError:objectdoesn'tsupportitemassignment
9
Tuple operations>>>x=(1,2,3)
>>>x+(2,)
(1,2,3,2)
• A 1-tuple is marked by (x,)
>>>x=(1,2,3)
>>>x
(1,2,3)
>>>x=1,2,3
>>>x
(1,2,3)
10
Tuple operations>>>range(10)
[0,1,2,3,4,5,6,7,8,9]
>>>tuple(range(10))
(0,1,2,3,4,5,6,7,8,9)
>>>tuple("ATGCCGCGAT")
('A','T','G','C','C','G','C','G','A','T')
• Use your imagination: we can have dictionaries of tuples, tuples of lists, list of tuples, etc.
11
Exercises1. Write a Python script to generate and print a dictionary that
contains number (between 1 and n) in the form (x, x*x). For n = 5, the expected output is: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
2. Write a Python program to multiply all the items in a dictionary.
3. Write a Python program to remove a key from a dictionary (del dict[key]).
4. Write a Python program to map two lists into a dictionary.
5. Write a Python program to sort a dictionary by key (sorted).
12
Functions• In programming, functions are very useful to solve
repeated tasks
• Functions make the code cleaner and easier to read
• For instance the range() function; range with the value 5 (range(5)) returns [0, 1, 2, 3, 4]; 5 is a parameter or an argument
• random.shuffle(), math.cos(), etc.
13
Functions
• A task
• Unique
• Precise
• (if it gets complicated, just break the problem into several functions)
14
Defining functions>>>defsquare(x):
...returnx**2
...
>>>printsquare(2)
4
>>>res=square(2)
>>>print(res)
4
15
Defining functions• return vs. no return
>>>defhello():
...print"bonjour"
...
>>>hello()
bonjour
>>>x=hello()
bonjour
>>>printx
None
16
Passing arguments>>>deftimes(x,y):
...returnx*y
...
>>>times(2,3)
6
>>>times(3.1415,5.23)
16.430045000000003
>>>times('to',2)
'toto'
17
Passing arguments>>>defsquare_cube(x):
...returnx**2,x**3
...
>>>square_cube(2)
(4,8)
>>>defsquare_cube2(x):
...return[x**2,x**3]
...
>>>square_cube2(3)
[9,27]
18
Passing arguments>>>defuseless_fct(x=1):
...returnx
...
>>>useless_fct()
1
>>>useless_fct(10)
10
• Facultative arguments after the mandatory ones:
deffct(x,y,z=1):
19
Variable scope>>>defmyfunction():
...x=2
...print'xis',x,'inthefunction'
...
>>>myfonction()
xis2inthefunction
>>>printx
Traceback(mostrecentcalllast):
File"<stdin>",line1,in?
NameError:name'x'isnotdefined
20
Variable scope>>>defmyfunction(x):
...print'xis',x,'inthefunction'
...
>>>myfunction(2)
xis2inthefunction
>>>printx
Traceback(mostrecentcalllast):
File"<stdin>",line1,in?
NameError:name'x'isnotdefined
21
Variable scope>>>defmyfunction():
...printx
...
>>>x=3
>>>myfunction()
3
>>>printx
3
22
Variable scope>>>defmyfunction():
...x=x+1
...
>>>x=1
>>>myfunction()
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
File"<stdin>",line2,infct
UnboundLocalError:localvariable'x'referencedbeforeassignment
23
Variable scope>>>defmyfunction():
...globalx
...x=x+1
...
>>>x=1
>>>myfunction()
>>>x
2
24
List scope>>>defmyfunction():
...liste[1]=-127
...
>>>liste=[1,2,3]
>>>myfunction()
>>>liste
[1,-127,3]
• Pay attention: lists can be modified in functions
25
List scope• Pass lists that you don't want to be modified as tuples or explicitly
>>>defmyfunction(x):
...x[1]=-15
...
>>>y=[1,2,3]
>>>myfunction(y[:])
>>>y
[1,2,3]
>>>myfunction(list(y))
>>>y
[1,2,3]
26
LGI• Local, Global, Internal (len())
>>>defmyfunction():
...x=4
...print'Inthefunctionxis',x
...
>>>x=-15
>>>myfunction()
Inthefunctionxis4
>>>print'Inthemainmodulexis',x
Inthemainmodulexis-15
27
Exercises (1)1. Predict the output of the following (without running the code):
defhello(name):
print("Hi",name)
hello("Patrick")
print(x)
2. Predict the output of the following (without running the code):
x=10
defhello(name):
print("Hi",name)
hello("Patrick")
print(x)
28
Exercises (2)3. Predict the output of the following (without running the code):
x=10
defhello(name):
print"Hi",name
printx
hello("Patrick")
printx
4. Predict the output of the following (without running the code):
x=10
defhello(name):
x=42
print"Hi",name
printx
hello("Patrick")
printx
29
Exercises (3)
5. Create a function that computes the Euclidean distance between two points in the 3D space. The points are represented as coordinate triplets (x, y, z).
6. Create a function that decides if a number is prime or not.
30
numpy
• python module
• Vectors and Matrices
• Arrays
31
Array objects>>>importnumpy
>>>a=[1,2,3]
>>>numpy.array(a)
array([1,2,3])
>>>b=numpy.array(a)
>>>type(b)
<type'numpy.ndarray'>
>>>b
array([1,2,3])
32
Array objects>>>numpy.arange(10)
array([0,1,2,3,4,5,6,7,8,9])
>>>numpy.arange(10.0)
array([0.,1.,2.,3.,4.,5.,6.,7.,8.,9.])
>>>numpy.arange(10,0,-1)
array([10,9,8,7,6,5,4,3,2,1])
>>>
33
Array objects>>>v=numpy.arange(4)
>>>v
array([0,1,2,3])
>>>v+1
array([1,2,3,4])
>>>v+0.1
array([0.1,1.1,2.1,3.1])
>>>v*2
array([0,2,4,6])
>>>v*v
array([0,1,4,9])
34
Array objects
>>>numpy.array([[1,2,3],[2,3,4],[3,4,5]])
array([[1,2,3],
[2,3,4],
[3,4,5]])
>>>
35
Array objects>>>numpy.array([[[1,2],[2,3]],[[4,5],[5,6]]])
array([[[1,2],
[2,3]],
[[4,5],
[5,6]]])
>>>
36
Array objects>>>a=numpy.arange(10)
>>>a
array([0,1,2,3,4,5,6,7,8,9])
>>>a[5:]
array([5,6,7,8,9])
>>>a[::2]
array([0,2,4,6,8])
>>>a[1]
1
37
Array objects>>>a=numpy.array([[1,2],[3,4]])
>>>a
array([[1,2],
[3,4]])
>>>a[:,0]
array([1,3])
>>>a[0,:]
array([1,2])
>>>a[1,1]
4
38
Array objects>>>numpy.zeros((3,3))
array([[0.,0.,0.],
[0.,0.,0.],
[0.,0.,0.]])
>>>numpy.zeros((3,3),int)
array([[0,0,0],
[0,0,0],
[0,0,0]])
>>>numpy.ones((3,3))
array([[1.,1.,1.],
[1.,1.,1.],
[1.,1.,1.]])
39
Array objects>>>a=numpy.arange(9)
>>>a
array([0,1,2,3,4,5,6,7,8])
>>>numpy.reshape(a,(3,3))
array([[0,1,2],
[3,4,5],
[6,7,8]])
40
Array objects>>>a=numpy.arange(9)
>>>a.reshape((2,2))
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
ValueError:totalsizeofnewarraymustbeunchanged
>>>numpy.resize(a,(2,2))
array([[0,1],
[2,3]])
>>>numpy.resize(a,(4,4))
array([[0,1,2,3],
[4,5,6,7],
[8,0,1,2],
[3,4,5,6]])
41
Array objects
>>>a=numpy.arange(3)
>>>numpy.shape(a)
(3,)
42
Array objects>>>a
array([[1,2,3],
[4,5,6],
[7,8,9]])
>>>numpy.transpose(a)
array([[1,4,7],
[2,5,8],
[3,6,9]])
43
Array objects>>>a=numpy.resize(numpy.arange(4),(2,2))
>>>a
array([[0,1],
[2,3]])
>>>numpy.dot(a,a)
array([[2,3],
[6,11]])
>>>a*a
array([[0,1],
[4,9]])
44
Matplotlib#definecosinefunction
frompylabimport*
debut=-2*pi
fin=2*pi
pas=0.1
x=arange(debut,fin,pas)
y=cos(x)
#drawtheplot
plot(x,y)
xlabel('angle(rad)')
ylabel('cos(angle)')
title('Fonction:y=cos(x)')
grid()
show()
45
Matplotlib
46
Matplotlib
47
• Check this out!
Exercises (1)1. Investigate the behavior of the statements below by looking at the values of the arrays a and b
after assignments: a = np.arange(5)
b=a
b[2]=-1
b=a[:]
b[1]=-1
b=a.copy()
b[0]=-1
2. Generate a 1D NumPy array containing numbers from -2 to 2 in increments of 0.2. Use optional start and step arguments of np.arange() function.
3. Create a 4x4 array with arbitrary values. Extract every element from the second row. Extract every element from the third column. Assign a value of 0.21 to upper left 2x2 subarray.
4. Plot the x squared function (x*x).
48