01 / 21

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.

Python

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

Base Case
The stopping condition: when the problem is small enough to answer directly, without making another recursive call. Without it, the function runs forever.
Recursive Case
The step where the function calls itself with a simpler or smaller input, moving closer to the base case with each call.

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):

factorial(4) factorial(3) factorial(2) factorial(1) factorial(0) = 1 returns 1 1 ✕ 1 = 1 2 ✕ 1 = 2 3 ✕ 2 = 6 4 ✕ 6 = 24 CALLS DOWN RETURNS UP

The Recursive Template

Every recursive function in Python follows this general pattern. Memorize this structure:

def solve(problem): # 1. Base case: simplest version if problem is simple_enough: return direct_answer # 2. Recursive case: break it down smaller = make_smaller(problem) sub_result = solve(smaller) # 3. Combine and return return combine(sub_result, problem)

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?"

1
Identify the smallest input. For numbers, it is often \( n = 0 \) or \( n = 1 \). For strings, it is the empty string \( "" \). For lists, it is \( [] \).
2
Know the answer directly. Factorial of \( 0 \) is \( 1 \). Sum of an empty list is \( 0 \). Length of \( "" \) is \( 0 \).
3
Make sure the recursive call reaches it. If you subtract \( 1 \) each time, the base case at \( n = 0 \) will be reached for all positive integers.

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

1
Define the function signature. What inputs does it take? What does it return?
2
Write the base case first. Handle the simplest input and return the known answer.
3
Assume the recursive call works. This is the "leap of faith": trust that solve(smaller) gives the correct result.
4
Combine the sub-result with the current input to form the full answer.
5
Test with small cases. Trace through \( n = 0 \), \( n = 1 \), \( n = 2 \) by hand to verify correctness.

Example 1: Factorial

Compute \( n! = n \times (n-1) \times \cdots \times 1 \), with \( 0! = 1 \).

def factorial(n): # Base case if n == 0: return 1 # Recursive case return n * factorial(n - 1)

Example 2: Sum of a List

Compute the sum of all elements in a list recursively.

def sum_list(lst): # Base case: empty list if lst == []: return 0 # Recursive case return lst[0] + sum_list(lst[1:])

Example 3: Fibonacci

The Fibonacci sequence: \( F(0) = 0 \), \( F(1) = 1 \), \( F(n) = F(n-1) + F(n-2) \).

def fibonacci(n): # Base cases (two!) if n == 0: return 0 if n == 1: return 1 # Recursive case: two recursive calls return fibonacci(n - 1) + fibonacci(n - 2)

Fibonacci Call Tree

Each call branches into two sub-calls, creating a tree. Notice how fib(2) is computed multiple times:

fib(4) fib(3) fib(2) fib(2) fib(1)=1 fib(1)=1 fib(0)=0 fib(1)=1 fib(0)=0 Duplicated work!

Example 4: Reverse a String

def reverse(s): # Base case: empty or single character if len(s) <= 1: return s # Recursive case return reverse(s[1:]) + s[0]

Example 5: Power Function

Compute \( x^n \) recursively. Base case: \( x^0 = 1 \).

def power(x, n): # Base case if n == 0: return 1 # Recursive case return x * power(x, n - 1)

Common Mistakes

✕ Missing Base Case
Forgetting the base case causes infinite recursion and a RecursionError. Always write the base case first.
✕ Not Making Progress
If the recursive call doesn't move toward the base case (e.g., calling f(n) instead of f(n-1)), it loops forever.
✕ Wrong Base Case Value
Returning the wrong value at the base (e.g., factorial(0) = 0 instead of 1) corrupts every result built on top.

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

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?