Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 9 Iteration: Recursion 5/02/09 Python Mini-Course: Day 3 - Lesson 9 1
Lesson objectives 1. Define recursion and state why recursion is useful 2. Use recursive functions 3. Use checkpoints to debug programs 5/02/09 Python Mini-Course: Day 3 - Lesson 9 2
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 5/02/09 Python Mini-Course: Day 3 - Lesson 9 3
Example: Blastoff def countdown(n): if n <= 0: print 'Blastoff!' else: print n countdown(n-1) countdown(10) 5/02/09 Python Mini-Course: Day 3 - Lesson 9 4
What's happening here? 5/02/09 Python Mini-Course: Day 3 - Lesson 9 5 Base class
Base classes All recursive functions must have a base class What happens otherwise? Try this: def recurse(): recurse() 5/02/09 Python Mini-Course: Day 3 - Lesson 9 6
Fibonacci sequence fibonacci(0) = 0 fibonacci(1) = 1 fibonacci(n) = fibonacci(n−1) + fibonacci(n−2) 5/02/09 Python Mini-Course: Day 3 - Lesson 9 7
Fibonacci sequence def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) \ + fibonacci(n-2) 5/02/09 Python Mini-Course: Day 3 - Lesson 9 8
Debugging with checkpoints 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 5/02/09 Python Mini-Course: Day 3 - Lesson 9 9
Testing preconditions Add a (temporary) print statement to the beginning of the function Use type-checking functions 5/02/09 Python Mini-Course: Day 3 - Lesson 9 10
Fibonacci sequence def fibonacci(n): print n, type(n) … fibonacci(-2) fibonacci(0.4) 5/02/09 Python Mini-Course: Day 3 - Lesson 9 11
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) 5/02/09 Python Mini-Course: Day 3 - Lesson 9 12
Testing postconditions 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 5/02/09 Python Mini-Course: Day 3 - Lesson 9 13
Next session More on loops and conditional execution Including the while loop Handling strings and text 5/02/09 Python Mini-Course: Day 3 - Lesson 9 14
Suggested exercises Exercise 6.5 – The Ackermann function Exercise 6.8 – Euclidean algorithm 5/02/09 Python Mini-Course: Day 3 - Lesson 9 15