Sub topic 11
Memoization: Avoiding Repeated Work
This chapter assumes you know how tree recursion works, where a function makes more than one recursive call. It also assumes you can read Python decorators and dictionaries. Memoization is a technique that stores the result of each call the first time it is computed. When the same input comes back, the function returns the stored answer and skips the recomputation.
Where the Repeated Work Comes From
Naive Fibonacci makes two calls per step. Those two calls share most of their subproblems. Counting the calls shows how fast the waste grows:
calls = 0
def fib(n):
global calls
calls += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10), calls) # 55 177Getting fib(10) takes 177 calls, even though only 11 distinct inputs exist (0 through 10). The call tree below shows the duplication for fib(4).
Writing a Memo by Hand
A memo is a lookup table, here a dictionary, that maps each input to its result. The function checks the memo before doing any work and saves its result before returning:
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(100)) # 354224848179261915075Each fib(k) is now computed once, so the work drops from exponential to linear in n.
Using functools.lru_cache
The standard library does the bookkeeping for you:
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)) # 354224848179261915075Common Errors
| Mistake | What goes wrong |
|---|---|
| Memoizing a function whose result depends on more than its arguments | It returns stale or wrong cached values |
| Passing unhashable arguments such as lists to `lru_cache` | It raises `TypeError: unhashable type` |
| Expecting memoization to reduce recursion depth | The first call to `fib(5000)` still nests about 5000 frames deep |
| Memoizing a function with no repeated subproblems | It uses extra memory and saves no time |
Memoization only pays off when subproblems overlap. Merge sort, covered in the next chapter, never solves the same subproblem twice, so caching would not help it.
Exercise
In naive fib(5), how many times is fib(3) computed, and how many times is fib(2) computed? With memoization, how many times is each computed?
Show answer
Without memoization, fib(3) is computed 2 times: once from fib(5) and once from fib(4). fib(2) is computed 3 times. With memoization, each is computed exactly once, and every later request is a lookup in the memo.
Exercise
Write a memoized function paths(r, c) that counts the paths from the top-left to the bottom-right of an r-by-c grid, moving only right or down. What does paths(3, 3) return?
Show answer
Use @lru_cache(maxsize=None) on: def paths(r, c): if r == 1 or c == 1: return 1; return paths(r - 1, c) + paths(r, c - 1). paths(3, 3) returns 6.