Sub topic 9
Memoization: Remembering Results
This chapter assumes you have read the earlier chapters on recursion trees and naive Fibonacci. You should be comfortable with Python functions, dictionaries, closures and decorators at a basic level, and Big-O notation. The naive fib from the previous chapter is the starting point. It recomputes the same values again and again, and memoization is the most direct way to stop that.
The working model
Memoization means storing the result of a function call the first time it is computed, keyed by its arguments. Each later call with the same arguments returns the stored result instead of recomputing it. The name comes from "memo", a note you write to yourself.
Three conditions make memoization worthwhile:
- Overlapping subproblems. The recursion tree contains the same call many times. Naive Fibonacci has this:
fib(3)appears twice insidefib(5), and the duplication grows exponentially withn. - Purity. The function's result depends only on its arguments. It does not read changing global state, and it has no side effects you need to repeat.
- Hashable arguments. The arguments can serve as dictionary keys.
If any of these fails, memoization either gains nothing or gives wrong answers.
Writing the cache by hand
Before using the standard library, build the cache yourself so the mechanism is visible. A closure keeps the dictionary private to one Fibonacci function:
def make_fib():
memo = {0: 0, 1: 1}
def fib(n):
if n in memo:
return memo[n]
memo[n] = fib(n - 1) + fib(n - 2)
return memo[n]
return fib
fib = make_fib()
print(fib(10)) # 55
print(fib(80)) # 23416728348467685The recursive structure is unchanged. The definition still says F(n) = F(n−1) + F(n−2) with F(0) = 0 and F(1) = 1. There are only two additions:
- a lookup before doing any work, and
- a store after the work is done.
The base cases are seeded into the dictionary, so the lookup handles them too.
Seeing the savings
Counting function entries makes the difference concrete. This script runs both versions on the same input and counts calls:
calls = 0
def fib_naive(n):
global calls
calls += 1
if n < 2:
return n
return fib_naive(n - 1) + fib_naive(n - 2)
def fib_counted(n, memo):
global calls
calls += 1
if n in memo:
return memo[n]
if n < 2:
result = n
else:
result = fib_counted(n - 1, memo) + fib_counted(n - 2, memo)
memo[n] = result
return result
for n in (10, 20, 30):
calls = 0
fib_naive(n)
naive_calls = calls
calls = 0
fib_counted(n, {})
memo_calls = calls
print(n, naive_calls, memo_calls)Output:
| n | Naive calls | Memoized calls |
|---|---|---|
| 10 | 177 | 19 |
| 20 | 21891 | 39 |
| 30 | 2692537 | 59 |
The naive count is 2·F(n+1) − 1, which grows like φⁿ (φ ≈ 1.618). The memoized count is 2n − 1 for n ≥ 1. Each value from 2 to n is computed exactly once, and each computation makes two calls. Every call beyond those is answered by a dictionary lookup in O(1) average time.
What the recursion tree becomes
Memoization prunes the recursion tree. The first time a subproblem appears, it expands as before. Every later appearance is a leaf, because it returns from the cache immediately.
The tree collapses to a single spine of depth n with one short branch at each level. That shape explains both costs:
- Time is O(n). There are n distinct subproblems, each does O(1) work outside its recursive calls, and the number of calls is about 2n.
- Space is O(n), split two ways. The cache holds n + 1 entries, and the call stack still reaches depth n on the first call because the spine is walked top to bottom before any value is stored.
Fibonacci values grow, so each addition is O(1) only while the numbers fit in a machine word. For large n, Python's arbitrary-precision integers make each addition cost proportional to the number of digits. That applies equally to every Fibonacci method in this tutorial.
Using `functools.lru_cache`
Python ships a memoizing decorator, so in practice you rarely write the dictionary yourself:
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(20)) # 6765
print(fib_memo.cache_info()) # CacheInfo(hits=18, misses=21, maxsize=None, currsize=21)With maxsize=None the cache never evicts anything. Python 3.9 and later also provide functools.cache, which is the same thing under a shorter name.
The cache_info() numbers match the model:
- 21 misses, one for each value from 0 to 20, each computed once.
- 18 hits. For each n from 3 to 20, the second recursive call,
fib_memo(n - 2), finds its value already stored.
Together they make the 39 calls counted earlier. Call fib_memo.cache_clear() to empty the cache, for example between timing runs.
Common errors
Hitting the recursion limit anyway
Memoization removes repeated work. It does not reduce stack depth on a cold cache. A first call to fib_memo(5000) walks 5000 frames down the spine before anything is cached, so CPython's default limit of about 1000 frames raises RecursionError. One fix is to warm the cache in ascending order, so each call only needs to go one level below values already stored:
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)
def fib_large(n):
for i in range(n + 1):
fib_memo(i)
return fib_memo(n)
print(len(str(fib_large(5000)))) # 1045Once you are filling values in ascending order, you are close to the bottom-up loop covered in the next chapter, which needs no cache and no deep stack at all.
The mutable default argument
This pattern appears often:
def fib(n, memo={}):
if n in memo:
return memo[n]
if n < 2:
return n
memo[n] = fib(n - 1, memo) + fib(n - 2, memo)
return memo[n]
print(fib(30)) # 832040It works because Python evaluates the default {} once, when the function is defined, so every call shares that one dictionary. The sharing is invisible at the call site. The cache also persists for the life of the program, and you cannot easily clear it or test the function with a fresh cache. Prefer a closure or lru_cache, which make the shared state explicit.
Unhashable arguments
lru_cache uses the arguments as dictionary keys. Passing a list raises TypeError: unhashable type: 'list'. Convert such arguments to tuples, or memoize on a hashable summary of the input, before the cached function sees them.
Memoizing impure functions
If a function depends on something other than its arguments, such as the current time, a global setting, or a file, the cache returns a stale answer the moment that outside state changes. Memoize only functions whose output is fully determined by their inputs.
Memoizing where nothing repeats
The linear recursive power function covered later calls power(x, n - 1), then power(x, n - 2), and so on, and each subproblem appears exactly once. Its recursion tree is a single chain with no overlap, so a cache only adds memory and lookup overhead. Before adding a cache, draw the recursion tree and look for repeated nodes.
When to choose memoization
| Situation | Memoization fits? | Reason |
|---|---|---|
| Recursive definition with overlapping subproblems | Yes | Turns exponential repetition into one computation per subproblem |
| Only some subproblems are actually needed | Yes | Top-down evaluation computes only what the recursion reaches |
| Depth of the first call exceeds the stack limit | With care | Warm the cache incrementally or switch to bottom-up |
| Recursion tree is a simple chain | No | Nothing repeats, so the cache is pure overhead |
| Function reads external state | No | Cached results go stale |
Memoization keeps the code close to the mathematical definition, which makes it easy to check against the recurrence and to argue correct by induction. The cache does not change what any call returns, only how quickly it returns. The cost is memory for the cache and stack depth on the first call.
Exercise
Using the hand-counted version fib_counted with a fresh empty dictionary, how many times is the function entered when computing fib(50)?
Show answer
99. Each value from 2 to 50 (49 values) is computed once and makes two calls, giving 98 calls, plus the initial call: 2·50 − 1 = 99.
Exercise
Starting from a fresh lrucache, you call fibmemo(20) and then fibmemo(25). What does fibmemo.cache_info() report afterwards for hits and misses?
Show answer
hits=24, misses=26. The first call gives 18 hits and 21 misses. The second call computes 21 through 25 (5 new misses). It also gets 6 hits: fib(20) and fib(19) inside fib(21), then the second call inside each of fib(22) through fib(25).
Exercise
The binomial coefficient satisfies C(n, k) = C(n−1, k−1) + C(n−1, k), with C(n, 0) = C(n, n) = 1. Does this recursion benefit from memoization, and roughly how many distinct subproblems does computing C(n, k) touch?
Show answer
Yes. The two branches overlap heavily; for example, C(n−2, k−1) is reached from both C(n−1, k−1) and C(n−1, k). The distinct subproblems are pairs (i, j) with i ≤ n and j ≤ k, so there are at most about (n+1)(k+1) of them. Memoization therefore gives O(n·k) time instead of time exponential in n.
Exercise
A colleague adds @lru_cache to the linear recursive power(x, n) and expects a speedup for a single call power(2, 500). Explain why it does not help.
Show answer
Its recursion tree is a single chain: power(x, n) calls power(x, n−1), and so on, and each subproblem occurs exactly once. The cache never produces a hit during one call, so it only adds memory use and hashing overhead.