Sub topic 1
What Makes a Function Recursive
Prerequisites
This chapter assumes you can write and call Python functions, use conditionals and loops, and read Big-O notation.
Base Case and Recursive Case
A recursive function calls itself on a smaller input. It needs two parts:
- Base case: an input small enough to answer directly, with no further calls.
- Recursive case: an answer built from the result of a call on a smaller input.
If there is no base case, or the input never shrinks toward one, the function never stops.
Factorial: The First Recursive Function
The definition is 0! = 1, and n! = n × (n−1)! for n > 0. The code follows it line for line:
def factorial(n):
if n < 0:
raise ValueError("n must be non-negative")
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120How the Call Stack Runs Recursive Calls
Each call gets a stack frame, which holds its own copy of n and the place to resume. factorial(3) pushes frames for 3, 2, 1 and 0. Only factorial(0) returns right away. The other frames then finish in reverse order, each multiplying its n by the value returned to it.
Why It Works: Induction
The code's structure gives you an induction proof:
- Base:
factorial(0)returns 1, which equals 0!. - Step: Assume
factorial(n-1)returns (n−1)!. Thenfactorial(n)returns n × (n−1)!, which is n!.
So the function is correct for every n ≥ 0. To check any recursive function, show that the base case is correct and that each recursive case is correct when the smaller calls are.
Recursion Depth Limits and Stack Overflow
Each pending call uses a frame. CPython stops at a recursion limit, 1000 frames by default, and raises RecursionError instead of crashing. This means factorial(5000) fails. A loop computes the same value with constant stack depth:
def factorial_iter(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial_iter(5)) # 120Exercise
Someone changes the base case to "if n == 1: return 1". What happens when they call factorial(0)?
Show answer
The call skips the base case and runs factorial(-1). The guard at the top raises ValueError. Without that guard, n would keep decreasing until Python raised RecursionError, because n would never reach 1.
Exercise
How many stack frames are active at the deepest point of factorial(4)?
Show answer
Five: one each for n = 4, 3, 2, 1 and 0.