Sub topic 5
Top-down DP with memoization
This chapter assumes you can write recursive Python functions, use dictionaries, and read Big-O notation. It also assumes you know the Fibonacci recurrence from earlier chapters: fib(n) = fib(n-1) + fib(n-2), with base cases fib(0) = 0 and fib(1) = 1.
Memoization keeps the recursive shape of a recurrence and adds a cache. Before computing a subproblem, the function checks whether it already has the answer. If it does, it returns the stored value. If not, it computes the value, stores it, and then returns it. Each distinct state is solved once, and every later request for it costs a dictionary lookup.
The lookup-compute-store pattern
Here is the pattern written out by hand:
def fib(n, memo=None):
if memo is None:
memo = {}
if n < 2:
return n
if n not in memo:
memo[n] = fib(n - 1, memo) + fib(n - 2, memo)
return memo[n]
print(fib(80)) # 23416728348467685Without the memo, fib(80) makes tens of trillions of calls. With it, each n from 2 to 80 is computed once, so the running time is O(n).
Why `memo=None` and not `memo={}`
Python evaluates a default argument once, when the function is defined. If you write memo={}, every top-level call shares the same dictionary. For Fibonacci the shared cache happens to give correct answers. In a function whose answers depend on other inputs, such as a coin list, the shared cache returns stale results from an earlier call. The None sentinel creates a fresh dictionary for each top-level call.
Letting `functools.lru_cache` do the bookkeeping
The standard library can add the cache for you. With maxsize=None the cache never evicts entries:
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)
fib.cache_clear()The decorator builds the key from the function's arguments, so every argument must be hashable. Convert lists to tuples before you pass them in. In Python 3.9 and later, functools.cache is shorthand for lru_cache(maxsize=None). Use cache_info() to check that hits are actually happening, and use cache_clear() to free memory or reset state between tests.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError: unhashable type: 'list'` | A list was passed to an `lru_cache` function | Pass a tuple, or keep the list outside the cached function and pass only indices |
| Wrong answers across calls | Mutable default `memo={}` or an incomplete key | Use `None` as the default; key on the full state |
| `RecursionError` for large `n` | Recursion depth exceeds Python's default limit of about 1000 | Warm the cache with smaller inputs first, raise the limit with care, or switch to tabulation |
| Still slow | The cache is checked after recursing, or never written | Look up the cache before recursing and store the result before returning |
Memoization only computes the states the recursion actually reaches. That helps when many states are never needed. The cost is one stack frame per level of recursion and the overhead of a function call for each state. The next chapter fills the same states in a loop instead.
Exercise
Memoize grid_paths(r, c), the number of ways to move from the top-left to cell (r, c) of a grid using only right and down moves. The recurrence is grid_paths(r, c) = grid_paths(r-1, c) + grid_paths(r, c-1), and grid_paths(r, c) = 1 when r == 0 or c == 0. What is grid_paths(16, 16), and how many distinct states does the cache hold after that call?
Show answer
Decorate the function with @lru_cache(maxsize=None), return 1 if r == 0 or c == 0, and otherwise return grid_paths(r - 1, c) + grid_paths(r, c - 1). The result is 601080390, which is C(32, 16). The cache holds every reachable (r, c) pair with 0 ≤ r, c ≤ 16 except (0, 0), because the recursion stops at (1, 0) and (0, 1) and never calls (0, 0). That is 17 × 17 − 1 = 288 entries, so cache_info().currsize is 288.
Exercise
A teammate writes def count(coins, amount, memo={}) and calls count([1, 2], 5) followed by count([5], 5). The memo is keyed on amount only. Why can the second call return the wrong answer?
Show answer
The default dictionary is created once and shared across calls. The key leaves out coins, so the second call finds entries cached for [1, 2] and returns them for [5]. Use memo=None with a fresh dictionary per top-level call, and either include the coins in the key or create a new cache for each coin set.