Download presentation
Presentation is loading. Please wait.
Published byAugustus Willis Modified over 9 years ago
1
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
2
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
3
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
4
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
5
What's happening here? 5/02/09 Python Mini-Course: Day 3 - Lesson 9 5 Base class
6
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
7
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
8
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
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 5/02/09 Python Mini-Course: Day 3 - Lesson 9 9
10
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
11
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
12
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
13
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
14
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
15
Suggested exercises Exercise 6.5 – The Ackermann function Exercise 6.8 – Euclidean algorithm 5/02/09 Python Mini-Course: Day 3 - Lesson 9 15
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.