Writing
Recursive Functions
Learn to design functions that call themselves, identify correct base cases, and build elegant solutions to problems that have self-similar structure.
What Is Recursion?
A recursive function is a function that calls itself during its execution. Instead of solving the whole problem at once, it breaks the problem into a smaller version of itself and delegates that smaller task to another call of the same function.
The Two Essential Parts
Visualizing the Call Stack
Each recursive call is pushed onto the call stack. When the base case is reached, results are returned back through each frame. Here is factorial(4):
The Recursive Template
Every recursive function in Python follows this general pattern. Memorize this structure:
Choosing the Right Base Case
The base case is the foundation of your recursion. Ask yourself: "What is the simplest possible input where I already know the answer?"
Recursion vs Iteration
| Recursion | Iteration | |
|---|---|---|
| Mechanism | Function calls itself | Loop repeats a block |
| Termination | Base case | Loop condition |
| Memory | Uses call stack (more) | Constant extra space |
| Readability | Elegant for trees/nested | Simpler for flat tasks |
| Risk | Stack overflow | Infinite loop |
Step-by-Step Approach
Example 1: Factorial
Compute \( n! = n \times (n-1) \times \cdots \times 1 \), with \( 0! = 1 \).
Example 2: Sum of a List
Compute the sum of all elements in a list recursively.
Example 3: Fibonacci
The Fibonacci sequence: \( F(0) = 0 \), \( F(1) = 1 \), \( F(n) = F(n-1) + F(n-2) \).
Fibonacci Call Tree
Each call branches into two sub-calls, creating a tree. Notice how fib(2) is computed multiple times:
Example 4: Reverse a String
Example 5: Power Function
Compute \( x^n \) recursively. Base case: \( x^0 = 1 \).
Common Mistakes
Recursion Summary
| Function | Base Case | Recursive Case |
|---|---|---|
| factorial(n) | \( n = 0 \to 1 \) | \( n \times \text{factorial}(n-1) \) |
| sum_list(lst) | lst == \( [] \to 0 \) | lst[0] + sum_list(lst[1:]) |
| fibonacci(n) | \( n \leq 1 \to n \) | fib(\(n-1\)) + fib(\(n-2\)) |
| reverse(s) | len(s) ≤ 1 \(\to\) s | reverse(s[1:]) + s[0] |
| power(x, n) | \( n = 0 \to 1 \) | \( x \times \text{power}(x, n-1) \) |
Question 1 of 5
What is the correct base case for a recursive function that computes \( n! \)?
Question 2 of 5
What happens if a recursive function has no base case?
Question 3 of 5
Consider this function:
def mystery(n):
if n == 0:
return 0
return n + mystery(n - 1)
What does mystery(4) return?
Question 4 of 5
A recursive function to count the length of a list should have what base case?
Question 5 of 5
Why does the Fibonacci function need two base cases instead of one?