Sub topic 9
Memoization: Remembering Results
This chapter assumes you can read Python functions and decorators, you know Big-O notation, and you have seen in the previous chapter that naive recursive fib(n) takes exponential time because it recomputes the same subproblems over and over.
The idea
Memoization means caching the result of a function call, keyed by its arguments. When the function is called again with the same arguments, it returns the stored result and skips the computation. The technique works on any pure function, meaning one whose result depends only on its arguments and which has no side effects. Fibonacci is a pure function.
The recursive structure stays the same. Each recursive call first checks the cache and computes only when the value is missing. Because there are only n + 1 distinct inputs (0 through n), at most n + 1 values are ever computed.
A hand-written cache
Writing the cache yourself makes the mechanism visible:
def fib_memo_dict(n, memo=None):
if memo is None:
memo = {}
if n < 2:
return n
if n in memo:
return memo[n]
memo[n] = fib_memo_dict(n - 1, memo) + fib_memo_dict(n - 2, memo)
return memo[n]
print(fib_memo_dict(80)) # 23416728348467685The same memo dictionary is passed down to every call, so a value computed in one branch can be used by another. The naive version would need roughly 10^16 calls for n = 80. This one finishes instantly.
The standard-library version
Python's functools.lru_cache wraps a function in the same kind of cache:
from functools import lru_cache
@lru_cache(maxsize=None)
def fib_memo(n):
if n < 2:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
print(fib_memo(80)) # 23416728348467685
print(fib_memo.cache_info())maxsize=None lets the cache grow without limit. cache_info() reports hits (results returned from the cache) and misses (results that had to be computed). On a fresh run of fib_memo(80) it reports 81 misses, one for each of 0..80, and 78 hits.
How the recursion tree shrinks
The first call to fib(n-1) goes all the way down the left spine and fills the cache. After that, every right-hand call fib(k-2) is a cache hit and ends immediately.
Each value from 2 to n is computed once, and each computation makes two calls, so the total is 2(n - 1) + 1 = 2n - 1 calls. The running time is O(n), and the cache uses O(n) extra space.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Writing `memo={}` as a default argument | The dictionary is shared across every top-level call and is never cleared | Use `memo=None` and create the dictionary inside the function |
| Creating a new dictionary on each recursive call | Branches cannot see each other's results, so the time goes back to exponential | Pass the same dictionary down every call |
| Passing a list or dictionary to an `lru_cache` function | `TypeError: unhashable type` | Use hashable arguments such as ints or tuples |
| Assuming memoization fixes recursion depth | The first call still recurses about `n` levels deep | Warm the cache in increasing order, or use a loop |
Exercise
Using fibmemodict, how many calls to the function happen in total when you compute fibmemodict(6) starting from an empty cache? Explain the count.
Show answer
11 calls. Each value from 2 to 6 (five values) is computed once, and each computation makes two calls, for 10 calls. Adding the original top-level call gives 11, which matches the formula 2n - 1 with n = 6.
Exercise
Right after a fresh fibmemo(80), you call fibmemo(81). How many new misses and hits does cache_info() record for that call?
Show answer
1 new miss and 2 new hits. fibmemo(81) is not cached, so it is a miss. It then calls fibmemo(80) and fib_memo(79), and both are already cached, so they are hits.