Sub topic 11
Memoization: Avoiding Repeated Work
This chapter assumes you can read Python functions and decorators, that you know how a recursive call makes a new stack frame, and that you have seen naive Fibonacci from the tree recursion chapter. The aim is to take a recursive function that repeats work and make it fast without changing its shape.
Where the Waste Comes From
Naive Fibonacci makes two recursive calls per step. Those calls overlap: fib(5) calls fib(4) and fib(3), and fib(4) calls fib(3) again. Every repeated subproblem grows its own full subtree of calls. You can count the calls directly:
calls = 0
def fib(n):
global calls
calls += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(20), calls) # 6765 21891Computing fib(20) takes 21,891 calls, even though only 21 distinct values (fib(0) through fib(20)) exist. The other 21,870 calls redo work that has already been done. This pattern is called overlapping subproblems: the same input shows up many times in the call tree.
The Idea: Remember Every Answer
Memoization stores the result of each call in a lookup table, keyed by the call's arguments. Before the function does any work, it checks the table. If the answer is already there, it returns it straight away. If not, it computes the answer, stores it, and then returns it.
This only works when a function is pure, meaning the same arguments always give the same result and the call has no side effects. Fibonacci qualifies. A function that reads the clock or changes a global does not.
A Hand-Written Memo
Writing the cache yourself shows exactly what happens:
def fib_memo(n, memo=None):
if memo is None:
memo = {}
if n in memo:
return memo[n]
if n < 2:
result = n
else:
result = fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
memo[n] = result
return result
print(fib_memo(20)) # 6765
print(fib_memo(90)) # 2880067194370816120The recursive structure is the same as before. Only two things were added: a lookup at the top and a store before returning. The memo dictionary is passed down so every call shares one table.
What the Call Tree Looks Like Now
With memoization, the first path down the left side of the tree computes fib(n-1), fib(n-2), and so on, all the way to the base cases. Each right-hand call then finds its answer already in the table.
Each value is computed once, and each computed node makes at most one extra call that turns out to be a hit. The work becomes linear in n instead of exponential. A later chapter shows how to state this cost formally with recurrence relations.
Using the Standard Library
Python ships memoization as a decorator. functools.lru_cache(maxsize=None) keeps every result. functools.cache (Python 3.9+) is a shorter name for the same thing.
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(30)) # 832040
print(fib.cache_info()) # CacheInfo(hits=28, misses=31, maxsize=None, currsize=31)cache_info() lets you check the behavior. There are 31 misses, one for each of fib(0) through fib(30), and 28 hits, one for each of fib(3) through fib(30) when it reuses fib(k-2). Call fib.cache_clear() to empty the cache, for example between benchmark runs.
With a finite maxsize, the cache evicts the least recently used entry when it fills up. That limits memory use, but a recursive function can lose entries it still needs, which brings back some of the repeated work.
Multiple Arguments
The cache key is the whole tuple of arguments, so functions with more than one parameter work the same way. This function counts the paths through an r by c grid when you can only move right or down:
from functools import cache
@cache
def paths(r, c):
if r == 1 or c == 1:
return 1
return paths(r - 1, c) + paths(r, c - 1)
print(paths(3, 3)) # 6
print(paths(18, 18)) # 2333606220Without the decorator, paths(18, 18) makes billions of calls. With it, there are at most 18 × 18 = 324 distinct subproblems.
Common Errors and Gotchas
Unhashable Arguments
The cache is a dictionary, so every argument has to be hashable. Lists, dicts, and sets are not.
from functools import cache
@cache
def total(items):
if not items:
return 0
return items[0] + total(items[1:])
print(total((3, 1, 4))) # 8
try:
total([3, 1, 4])
except TypeError as e:
print("TypeError:", e) # TypeError: unhashable type: 'list'Pass a tuple or a frozenset instead, or cache on a smaller key such as an index into a list that does not change. This example also shows that memoization does nothing when subproblems never repeat. Each suffix of the tuple occurs exactly once, so the cache only uses up memory.
Memoization Does Not Fix Stack Depth
A cold cache still needs the full chain of calls down to the base case. On a typical CPython build with a recursion limit of 1000, the first call to memoized fib(5000) raises RecursionError, even though the result would only take 5,000 steps. You can warm the cache from the bottom up (for k in range(5000): fib(k)) so each call only goes a few frames deep, or you can drop recursion altogether.
Caching Impure Functions
If a function's result depends on anything besides its arguments, such as a file, the time, or a mutable global, the cache returns stale answers. Memoize only pure functions.
Methods and Memory
Putting @cache on a method includes self in the key. That keeps every instance alive as long as the cache exists. For long-running programs, cache a module-level helper function or clear the cache explicitly.
Top-Down Versus Bottom-Up
Memoization is the top-down approach. You keep the recursive definition and add a cache to it. The bottom-up approach, called tabulation, computes subproblems in dependency order with a loop:
def fib_table(n):
if n < 2:
return n
prev, curr = 0, 1
for _ in range(n - 1):
prev, curr = curr, prev + curr
return curr
print(fib_table(10)) # 55
print(fib_table(5000) % 1000) # last three digits, no RecursionError| Aspect | Memoization (top-down) | Tabulation (bottom-up) |
|---|---|---|
| Code shape | Same as the recursive definition | Loop with an explicit evaluation order |
| Subproblems computed | Only those actually reached | Usually all of them |
| Stack depth | Grows with recursion depth | Constant |
| Memory | Cache holds every result | Often reducible to a few variables |
| Effort to write | Add one decorator | Requires working out the order |
Start with memoization when the recursive version is clear and the input sizes are moderate. Switch to tabulation when depth limits or memory become a problem.
Exercise
Without running it, predict what fib.cache_info() reports after calling the lru_cache version as fib(10) on an empty cache, then again after calling fib(12).
Show answer
After fib(10): misses=11 (fib(0) through fib(10)) and hits=8 (fib(3) through fib(10) each reuse fib(k-2)), currsize=11. Calling fib(12) then misses on fib(12) and fib(11). fib(12) calls fib(11), and fib(11) calls fib(10) and fib(9), which are both hits. fib(12) then calls fib(10), another hit. Totals: misses=13, hits=11, currsize=13.
Exercise
A function count_ways(n, coins) counts the ways to make n from a list of coin values, recursing on count_ways(n - coins[0], coins) and count_ways(n, coins[1:]). Adding @cache raises TypeError. Give two fixes.
Show answer
The list coins is unhashable. Fix 1: pass coins as a tuple, so slices are tuples too and the arguments can be hashed. Fix 2: keep the coins in a fixed list outside the cached function and recurse on an index, ways(n, i), using coins[i] and ways(n, i + 1). The cache key is then just two integers.