Day 2 – Lesson 9 Iteration: Recursion Python Mini-Course University of Oklahoma Department of Psychology Python Mini-Course: Day 3 - Lesson 9 5/02/09
Download ReportTranscript Day 2 – Lesson 9 Iteration: Recursion Python Mini-Course University of Oklahoma Department of Psychology Python Mini-Course: Day 3 - Lesson 9 5/02/09
Day 2 – Lesson 9 Iteration: Recursion Python Mini-Course University of Oklahoma Department of Psychology 1 Python Mini-Course: Day 3 - Lesson 9 5/02/09
Lesson objectives
1.
2.
3.
Define recursion and state why recursion is useful Use recursive functions Use checkpoints to debug programs 2 Python Mini-Course: Day 3 - Lesson 9 5/02/09
Recursion
Not only can functions call other functions (composition), they can also call themselves This is called recursion Recursion is a powerful method that is a key component to functional programming 3 Python Mini-Course: Day 3 - Lesson 9 5/02/09
Example: Blastoff
def countdown(n): if n <= 0: print 'Blastoff!' else: print n countdown(n-1) countdown(10) 4 Python Mini-Course: Day 3 - Lesson 9 5/02/09
What's happening here?
5 Python Mini-Course: Day 3 - Lesson 9 Base class 5/02/09
Base classes
6 All recursive functions must have a base class What happens otherwise?
Try this: def recurse(): recurse() recurse() Python Mini-Course: Day 3 - Lesson 9 5/02/09
Fibonacci sequence
fibonacci(0) = 0 fibonacci(1) = 1 fibonacci(n) = fibonacci(n−1) + fibonacci(n−2) 7 Python Mini-Course: Day 3 - Lesson 9 5/02/09
Fibonacci sequence
def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) \ + fibonacci(n-2) 8 Python Mini-Course: Day 3 - Lesson 9 5/02/09
Debugging with checkpoints
9 If a function is not working check: Preconditions Arguments being passed into the function Postconditions Operations in the function itself The way the function is being used Python Mini-Course: Day 3 - Lesson 9 5/02/09
Testing preconditions
Add a (temporary) print statement to the beginning of the function Use type-checking functions 10 Python Mini-Course: Day 3 - Lesson 9 5/02/09
Fibonacci sequence
def fibonacci(n): print n, type(n) … fibonacci(-2) fibonacci(0.4) 11 Python Mini-Course: Day 3 - Lesson 9 5/02/09
Fibonacci sequence
def fibonacci(n): if (not type(n) == int) or n < 0: print "Fibonacci is only \ defined for non-negative \ integers" return … fibonacci(-2) 12 Python Mini-Course: Day 3 - Lesson 9 5/02/09
Testing postconditions
13 Use same technique of adding (temporary) print statements at critical points in the function For large programs or functions, use the half-splitting technique Check beginning, middle, end Find the half with a problem Recurse Python Mini-Course: Day 3 - Lesson 9 5/02/09
Next session
More on loops and conditional execution Including the while loop Handling strings and text 14 Python Mini-Course: Day 3 - Lesson 9 5/02/09
Suggested exercises
Exercise 6.5 – The Ackermann function Exercise 6.8 – Euclidean algorithm 15 Python Mini-Course: Day 3 - Lesson 9 5/02/09