Download presentation

Presentation is loading. Please wait.

Published byAlvin Straughan Modified about 1 year ago

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

2
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)

3
INCREMENTAL DEVELOPMENT One 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

4
CONTINUING WE HAVE def 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 4 so the answer should be 8 You might need to check other cases as well for some functions

5
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!

6
COMPOSITION It 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!

7
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)

8
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 requirementsborn abroad Note that the definition of citizenship is defined recursively!

9
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 factorials for i in range(10): print factorial(i) output is Just how big a factorial can Python handle?

10
HERE IS THEN END OF FACTORIAL(50) Try factorial(100) or more

11
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 Its definition is almost always stated recursively Fib(1) = 1 Fib(2) = 1 Fib(n) = Fib(n-1) + F(n-2) and so on. +

12
FIBONACCI IN PYTHON Definition is Fib(1) = 1 Fib(2) = 1 Fib(n) = Fib(n-1) + F(n-2) #method 1 def Fib(n): if n==1: return 1 elif n==2: return 2 else: return Fib(n-1)+Fib(n-2) #method 2 def Fib(n): if n==1 or n==2: return 1 else: return Fib(n-1)+Fib(n-2)

13
A RUN def 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), >>> >>> As n in Fib(n) gets larger something happens. Try Fib(30)

14
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?

15
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 code If the argument is incorrect get out of here! Returns true if n is an integer! There a little issue here? It slows it down somewhat!

16
A STRING EXAMPLE Write 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?

17
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

Similar presentations

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google