Sub topic 3
Memoization: Avoiding Repeated Work
This chapter assumes you can write recursive functions with a base case and can read a call tree. It covers the costs of recursion and the main techniques for managing them.
Memoization
Naive fib(n) calls fib(n - 2) from two places, so the same subproblems are solved again and again and the work grows exponentially. Memoization means storing each result the first time you compute it and reusing it after that. With memoization, each fib(k) runs only once.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(100)) # 354224848179261915075Divide and Conquer: Merge Sort
Merge sort splits the list in half, sorts each half recursively, and then merges the two sorted halves.
def merge_sort(items):
if len(items) <= 1:
return items
mid = len(items) // 2
left, right = merge_sort(items[:mid]), merge_sort(items[mid:])
merged, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i]); i += 1
else:
merged.append(right[j]); j += 1
return merged + left[i:] + right[j:]
print(merge_sort([5, 2, 9, 1, 3])) # [1, 2, 3, 5, 9]Stack Depth Limits
Every pending call holds a stack frame. CPython caps the depth of the call stack, usually at 1000 frames, and raises RecursionError when a chain of calls goes past it. A loop has no such limit. You can check the current cap with sys.getrecursionlimit().
Backtracking
Backtracking works in three steps: make a choice, recurse to explore it, then undo the choice so the next option starts from the same state.
def permutations(items):
results, current = [], []
def backtrack():
if len(current) == len(items):
results.append(current[:])
return
for x in items:
if x not in current:
current.append(x)
backtrack()
current.pop()
backtrack()
return results
print(permutations([1, 2, 3]))This version uses x not in current to skip items already chosen, so it assumes the items are distinct.
Mutual Recursion
In mutual recursion, two functions call each other. For example, is_even(n) calls is_odd(n - 1), and is_odd(n) calls is_even(n - 1). Both shrink n, so they reach a shared base case at 0.
Recurrence Relations
A recurrence relation describes the cost of a recursive function in terms of the cost of its smaller calls.
| Function | Recurrence | Time |
|---|---|---|
| Naive `fib` | T(n) = T(n-1) + T(n-2) + O(1) | O(φⁿ) |
| Memoized `fib` | each n computed once | O(n) |
| Merge sort | T(n) = 2T(n/2) + O(n) | O(n log n) |
The stack space a recursive function needs equals its maximum call depth. That is O(n) for fib and O(log n) for merge sort.
Tail Recursion
A call is a tail call when it is the last thing the function does. The accumulator version of factorial below is tail recursive. Scheme guarantees tail-call optimization and would run it in constant stack space. CPython does not optimize tail calls, so this version still uses one frame per call.
def factorial_acc(n, acc=1):
if n == 0:
return acc
return factorial_acc(n - 1, acc * n)Rewriting Recursion with an Explicit Stack
You can replace the call stack with a list that you manage yourself. This avoids the depth limit.
class Node:
def __init__(self, value, left=None, right=None):
self.value, self.left, self.right = value, left, right
def tree_sum(root):
total, stack = 0, [root] if root else []
while stack:
node = stack.pop()
total += node.value
if node.right: stack.append(node.right)
if node.left: stack.append(node.left)
return total
print(tree_sum(Node(1, Node(2, Node(4)), Node(3)))) # 10Exercise
Why does memoized fib(5000) still fail in CPython even though it does only linear work?
Show answer
The first call recurses about 5000 levels deep before any cached result is available. That exceeds the default recursion limit and raises RecursionError.