Recursion
The recipe
Every recursive function needs:
- A base case: the smallest version, answered directly. This stops the recursion.
- A recursive case: solve a smaller version, then combine.
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1) # smaller problem
How to think about it: trust the function
Assume factorial(n - 1) already works, and only figure out how to use it to build factorial(n). Don't try to trace every call in your head.
The call stack
Each call waits on the stack until the smaller call returns. Python's default limit is about 1000 calls deep, after which you get RecursionError. For very deep problems, use a loop.
Overlapping work and memoisation
Naive Fibonacci recomputes the same values again and again: O(2ⁿ). Caching results with @lru_cache makes it O(n). This is the bridge to dynamic programming (Unit 11).
Where recursion shines
Trees, nested folders, divide and conquer (merge sort), permutations and backtracking: anything that naturally contains smaller copies of itself.
Complexity
Count the calls × the work per call. Space = the maximum depth of the call stack.
Example
from functools import lru_cache
def factorial(n):
return 1 if n <= 1 else n * factorial(n - 1)
def power(base, exp): # fast power: O(log exp)
if exp == 0:
return 1
half = power(base, exp // 2)
return half * half * (base if exp % 2 else 1)
@lru_cache(maxsize=None)
def fib(n): # O(n) thanks to the cache
return n if n < 2 else fib(n - 1) + fib(n - 2)
def flatten(nested): # recursion on nested data
out = []
for item in nested:
out.extend(flatten(item) if isinstance(item, list) else [item])
return out
print(factorial(5)) # 120
print(power(2, 10)) # 1024
print(fib(60)) # 1548008755920
print(flatten([1, [2, [3, [4]], 5]])) # [1, 2, 3, 4, 5]