1 / 17

Python Fruitful functions chapter 6

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

decker
Download Presentation

Python Fruitful functions chapter 6

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PythonFruitful functionschapter 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 requirements • Note that the definition of citizenship is defined recursively!

  9. Factorial in Python recursively # print the first 10 factorials for i in range(10): print factorial(i) output is 1 2 6 24 120 720 5040 40320 362880 3628800 • def factorial(n) • if n == 0: • return 1 • else: • return n * factorial(n-1) • Test this out! Just how big a factorial can Python handle?

  10. 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

  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 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. +

  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==1or 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), • >>> • 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)

  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 Returns true if n is an integer! • 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! 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[1:-1] word[0] word[-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

More Related