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