python fruitful functions chapter 6

17
PYTHON FRUITFUL FUNCTIONS CHAPTER 6 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST

Upload: decker

Post on 08-Feb-2016

43 views

Category:

Documents


3 download

DESCRIPTION

Python Fruitful functions chapter 6. From Think Python How to Think Like a Computer Scientist. Return Values. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Python Fruitful functions chapter 6

PYTHONFRUITFUL FUNCTIONSCHAPTER 6

FROM

THINK PYTHON

HOW TO THINK LIKE A COMPUTER SCIENTIST

Page 2: Python Fruitful functions chapter 6

RETURN VALUES

The majority of functions return a value such as those we have been using from the math module such as sqrt(), sin() and atan2(). We of course can write our own and will do so often. Lets look at a few as examples(math is assumed to be imported)

def absolute_value(x)

if x<0:

return –x

else:

return x

def VolumeSphere(r) v = 4/3*pi*r**3

def distance(x1,y1,x2,y2) temp = (x2-x1)**2+(y2-y1)**2 return sqrt(temp)

Page 3: Python Fruitful functions chapter 6

INCREMENTAL DEVELOPMENTOne does not need to write the entire function initially during development. Start with as “stub” and let it grow!! For example we could start the distance function this way.

def distance(x1,y1,x2,y2)

return 0

We can then test it to see if the call works. Simple things can be tested within the interactive mode or in script mode if they are more complicated.

>>>distance(2,1,3,4)

0

Page 4: Python Fruitful functions chapter 6

CONTINUING WE HAVEdef distance(x1,y1,x2,y2)

temp = (x2-x1)**2+(y2-y1)**2

return temp

#And test it

>>>distance(1,2,3,4)

8

#And then the final step is

def distance(x1,y1,x2,y2)

temp = (x2-x1)**2+(y2-y1)**2

return sqrt(temp)

Check this by hand(3-1)**2 is 4(4-2)**2 is 4so the answer should be 8

You might need to check other cases as well for some functions

Page 5: Python Fruitful functions chapter 6

INTERMEDIATE PRINTING

def distance(x1,y1,x2,y2)

temp = (x2-x1)**2+(y2-y1)**2

print ‘The value of temp is’,temp

return sqrt(temp)

Generally you should slowly build a function by adding a line at a time, often using prints to check intermediate results. Study the example in chapter 6.0

This is very important to do. WHY.

BECAUSE when something goes wrong YOU know where the error is. CAPICE!

Page 6: Python Fruitful functions chapter 6

COMPOSITIONIt is often the case that you call functions within functions. Here is an example you may have already seen

def polygon(t,n,length):

angle = 360.0/n

for i in range(n):

fd(t,length)

lt(t,angle)

def circle(t,r):

circumference = 2 * pi * r

n = int(circumference /3)+1

length = circumference / n

polygon(t,n,length)

Be sure and put polygon()before circle() in the script!

Page 7: Python Fruitful functions chapter 6

RECURSION

It is even ok to call yourself !!!!!!! If you do so it is called recursion. Lets look at a very simple example. You may recall that the mathematical operation factorial looks like

5! = 5*4*3*2*1

or in general

N! = N*(N-1)*(N-2)*(N-3) * … * 2*1

or it can be defined in terms of itself as

N! = N * (N-1)! where 0! =1

(base case)

Page 8: Python Fruitful functions chapter 6

AN INTERESTING EXAMPLE

To become a citizen at birth, you must:

Have been born in the United States or certain territories or outlying possessions of the United States, and subject to the jurisdiction of the United States; OR     

had a parent or parents who were citizens at the time of your birth (if you were born abroad) and meet other requirements

Note that the definition of citizenship is defined recursively!

Page 9: Python Fruitful functions chapter 6

FACTORIAL IN PYTHON RECURSIVELY

def factorial(n)

if n == 0:

return 1

else:

return n * factorial(n-1)

Test this out!

# print the first 10 factorialsfor i in range(10): print factorial(i)

output is126241207205040403203628803628800

Just how big a factorial can Python handle?

Page 10: Python Fruitful functions chapter 6

HERE IS THEN END OF FACTORIAL(50).. .. .. .. .. .. ..

2432902008176640000

51090942171709440000

1124000727777607680000

25852016738884976640000

620448401733239439360000

15511210043330985984000000

403291461126605635584000000

10888869450418352160768000000

304888344611713860501504000000

8841761993739701954543616000000

265252859812191058636308480000000

8222838654177922817725562880000000

263130836933693530167218012160000000

8683317618811886495518194401280000000

295232799039604140847618609643520000000

10333147966386144929666651337523200000000

371993326789901217467999448150835200000000

Try factorial(100) or more

Page 11: Python Fruitful functions chapter 6

FIBONACCI SEQUENCE

The Fibonacci sequence is very well known. It has a serious relationship with biological feedback loops (rabbit reproduction, cellular growth, botanical structure etc.)

see http://www.mscs.dal.ca/Fibonacci/index.html

Its definition is almost always stated recursively

Fib(1) = 1

Fib(2) = 1

Fib(n) = Fib(n-1) + F(n-2)

1 1 2 3 5 8 13 21 34 55 and so on.+

Page 12: Python Fruitful functions chapter 6

FIBONACCI IN PYTHONDefinition is

Fib(1) = 1

Fib(2) = 1

Fib(n) = Fib(n-1) + F(n-2)

#method 1def Fib(n): if n==1: return 1 elif n==2: return 2 else: return Fib(n-1)+Fib(n-2)

#method 2def Fib(n): if n==1 or n==2: return 1 else: return Fib(n-1)+Fib(n-2)

Page 13: Python Fruitful functions chapter 6

A RUNdef Fib(n):

if n==1 or n==2:

return 1

else:

return Fib(n-1)+Fib(n-2)

for i in range(20):

print Fib(i+1),

>>>

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

>>>

As n in Fib(n) gets larger something happens. Try Fib(30)

Page 14: Python Fruitful functions chapter 6

WHAT IF YOU REQUEST FIB(2.2)?You get something like the following.

File "C:/PythonCode/factorial.py", line 7, in Fib

return Fib(n-1)+Fib(n-2)

File "C:/PythonCode/factorial.py", line 7, in Fib

return Fib(n-1)+Fib(n-2)

…………………………….

File "C:/PythonCode/factorial.py", line 7, in Fib

return Fib(n-1)+Fib(n-2)

File "C:/PythonCode/factorial.py", line 7, in Fib

return Fib(n-1)+Fib(n-2)

File "C:/PythonCode/factorial.py", line 4, in Fib

if n==1 or n==2:

RuntimeError: maximum recursion depth exceeded in cmp

>>>

What’s up with that?

Page 15: Python Fruitful functions chapter 6

WE CAN CHECK THE ARGUMENT TYPE def Fib(n):

if not isinstance(n,int):

print ‘Fib is only defined for integers.’

return # Don’t return a value here

if n<0:

print ‘Fib is not defined for negative numbers’

return # Don’t return a value or here

if n==1 or n==2:

return 1

else:

return Fib(n-1)+Fib(n-2)

Guardian codeIf the argumentis incorrect getout of here!

Returns true if n isan integer!

There a little issue here?

It slows it down somewhat!

Page 16: Python Fruitful functions chapter 6

A STRING EXAMPLEWrite a recursive function to test if a string is a palindrome.

Remember we can access each character in a string via subscripting.

Name = ‘risttsir’

Here Name[0] is r, Name[1] is I, Name[2] is s , and so on

Also Name[-1] is the last character of the string, i.e. r

To test for this attribute we can do the following

if the first char is equal to the last character

and the middle section is a palindrome then

the string is a palindrome. You agree?

Page 17: Python Fruitful functions chapter 6

THE CODE ( A BOOLEAN EXAMPLE)

word = ‘asdfghiihgfdsa’

word[0] word[-1]word[1:-1]

def is_palin(w): if len(w)==0 or len(w)==1: #base case return True if w[0]==w[-1]: # is first == last? return is_palin(w[1:-1]) #this is the middle else: return False