python 5 - lsis · write a python script to generate and print a dictionary that ... write a python...

48
Python 5 Dictionaries, Functions, numpy 1

Upload: lamque

Post on 29-Aug-2018

302 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Python 5Dictionaries, Functions, numpy

1

Page 2: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Goals (today)

• Dictionaries and tuples

• Functions: principles, definitions, argument passage

• numpy: presentation, useful functions

• Exercises

2

Page 3: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Project (2)

• Check the project on my page (Teachings / NEW! Big Data: Introduction to python (EN) / Projects)

3

Page 4: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Dictionaries

• Very practical for complex data structures

• Non ordered object collections

• Key-value pairs

4

Page 5: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 6: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 7: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 8: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Key existence>>>ifani2.has_key('weight'):

...print"Thekey'weight'existsforani2"

...

Thekey'weight'existsforani2

>>>if"weight"inani2:

...print"Thekey'weight'existsforani2"

...

Thekey'weight'existsforani2

8

Page 9: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 10: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 11: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 12: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 13: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 14: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Functions

• A task

• Unique

• Precise

• (if it gets complicated, just break the problem into several functions)

14

Page 15: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Defining functions>>>defsquare(x):

...returnx**2

...

>>>printsquare(2)

4

>>>res=square(2)

>>>print(res)

4

15

Page 16: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Defining functions• return vs. no return

>>>defhello():

...print"bonjour"

...

>>>hello()

bonjour

>>>x=hello()

bonjour

>>>printx

None

16

Page 17: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Passing arguments>>>deftimes(x,y):

...returnx*y

...

>>>times(2,3)

6

>>>times(3.1415,5.23)

16.430045000000003

>>>times('to',2)

'toto'

17

Page 18: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 19: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 20: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Variable scope>>>defmyfunction():

...x=2

...print'xis',x,'inthefunction'

...

>>>myfonction()

xis2inthefunction

>>>printx

Traceback(mostrecentcalllast):

File"<stdin>",line1,in?

NameError:name'x'isnotdefined

20

Page 21: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Variable scope>>>defmyfunction(x):

...print'xis',x,'inthefunction'

...

>>>myfunction(2)

xis2inthefunction

>>>printx

Traceback(mostrecentcalllast):

File"<stdin>",line1,in?

NameError:name'x'isnotdefined

21

Page 22: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Variable scope>>>defmyfunction():

...printx

...

>>>x=3

>>>myfunction()

3

>>>printx

3

22

Page 23: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 24: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Variable scope>>>defmyfunction():

...globalx

...x=x+1

...

>>>x=1

>>>myfunction()

>>>x

2

24

Page 25: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

List scope>>>defmyfunction():

...liste[1]=-127

...

>>>liste=[1,2,3]

>>>myfunction()

>>>liste

[1,-127,3]

• Pay attention: lists can be modified in functions

25

Page 26: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 27: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

LGI• Local, Global, Internal (len())

>>>defmyfunction():

...x=4

...print'Inthefunctionxis',x

...

>>>x=-15

>>>myfunction()

Inthefunctionxis4

>>>print'Inthemainmodulexis',x

Inthemainmodulexis-15

27

Page 28: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 29: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 30: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 31: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

numpy

• python module

• Vectors and Matrices

• Arrays

31

Page 32: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 33: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 34: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 35: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Array objects

>>>numpy.array([[1,2,3],[2,3,4],[3,4,5]])

array([[1,2,3],

[2,3,4],

[3,4,5]])

>>>

35

Page 36: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Array objects>>>numpy.array([[[1,2],[2,3]],[[4,5],[5,6]]])

array([[[1,2],

[2,3]],

[[4,5],

[5,6]]])

>>>

36

Page 37: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 38: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 39: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 40: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 41: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 42: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Array objects

>>>a=numpy.arange(3)

>>>numpy.shape(a)

(3,)

42

Page 43: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 44: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 45: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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

Page 46: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Matplotlib

46

Page 47: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

Matplotlib

47

• Check this out!

Page 48: Python 5 - LSIS · Write a Python script to generate and print a dictionary that ... Write a Python program to multiply all the items in a ... debut = -2 * pi fin = 2 * pi

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