Presentation on theme: "PYTHON FRUITFUL FUNCTIONS CHAPTER 6 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST."— Presentation transcript:
PYTHON FRUITFUL FUNCTIONS CHAPTER 6 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST
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)
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
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
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!
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!
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)
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!
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 1 2 6 24 120 720 5040 40320 362880 3628800 Just how big a factorial can Python handle?
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
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.htmlhttp://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. +
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)
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)
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?
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!
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 is r, Name is I, Name 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?
THE CODE ( A BOOLEAN EXAMPLE) word = ‘asdfghiihgfdsa’ word word[-1] word[1:-1] def is_palin(w): if len(w)==0 or len(w)==1: #base case return True if w==w[-1]: # is first == last? return is_palin(w[1:-1]) #this is the middle else: return False