Sub topic 13
Memoization and Bottom-Up Iteration
This chapter assumes you can read Python functions and loops, follow Big-O notation, and recognize the repeated work in naive tree recursion from the chapter on multiple recursion. Here you will remove that repeated work in two ways. Memoization keeps the recursive shape and caches results. Bottom-up iteration drops recursion and fills in results in dependency order with a loop.
The Problem: Same Subproblem, Many Calls
Naive Fibonacci calls fib(n - 1) and fib(n - 2), and each of those makes two more calls. The subproblems overlap: fib(3) is computed again in every branch that needs it. The answer depends on only n + 1 distinct inputs, yet the number of calls grows exponentially.
Counting the calls shows the gap:
calls = {"naive": 0, "memo": 0}
def fib_naive(n):
calls["naive"] += 1
if n < 2:
return n
return fib_naive(n - 1) + fib_naive(n - 2)
def fib_memo_dict(n, memo=None):
calls["memo"] += 1
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_naive(20), calls["naive"]) # 6765 21891
print(fib_memo_dict(20), calls["memo"]) # 6765 39Both functions return 6765. The naive version makes 21,891 calls. The memoized version makes 39: each value from 2 to 20 is computed once and makes two calls, plus the first call.
Memoization: Top-Down Caching
Memoization stores each result the first time it is computed. Every later call with the same arguments returns the stored value without recomputing it. The function is still recursive and still starts from the top (n), working down to the base cases.
The hand-written version above shows three rules:
- Check the base case.
- Check the cache before doing any work.
- Store the result before returning it.
Python's standard library does this for you with functools.lru_cache (or functools.cache in Python 3.9+):
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()) # hits, misses, maxsize, currsize
fib_memo.cache_clear() # empty the cacheThe decorator keys the cache on the call's arguments. maxsize=None means the cache never evicts entries.
Common Errors with Memoization
| Error | Symptom | Fix |
|---|---|---|
| Unhashable arguments to `lru_cache` | `TypeError: unhashable type: 'list'` | Pass tuples or other immutable values, or key the cache on an index |
| Checking the cache after recursing | No speedup | Look up the cache before making recursive calls |
| Forgetting to store the result | Exponential time comes back | Assign into the cache before `return` |
| Memoizing a function with side effects or hidden inputs | Stale or wrong results | Memoize only pure functions whose output depends only on arguments |
| Unbounded cache in a long-running process | Memory keeps growing | Set `maxsize`, or call `cache_clear()` |
The Depth Problem Memoization Does Not Fix
Memoization cuts the time from exponential to O(n), but it does not reduce stack depth. On a cold cache, the first call to fib_memo(n) still descends through n, n - 1, ..., 1 before any value is stored. That takes O(n) stack frames, and CPython's default limit is about 1000.
import sys
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(sys.getrecursionlimit()) # typically 1000
try:
fib_memo(5000)
except RecursionError:
print("RecursionError on a cold cache")
fib_memo.cache_clear()
for i in range(0, 5001, 200): # warm the cache in small steps
fib_memo(i)
print(len(str(fib_memo(5000)))) # 1045 digitsWarming the cache in steps works because each call only descends to the nearest cached value. This is a workaround, though. If inputs can be large, the better fix is to remove the recursion entirely.
Bottom-Up Iteration: Filling a Table
Bottom-up iteration reverses the direction. Instead of starting at n and asking for smaller answers, you start at the base cases and build upward until you reach n. A loop replaces the recursion, so there is no stack growth at all.
The direct translation fills a table in order:
def fib_table(n):
if n < 2:
return n
table = [0] * (n + 1)
table[1] = 1
for i in range(2, n + 1):
table[i] = table[i - 1] + table[i - 2]
return table[n]
print(fib_table(80)) # 23416728348467685Each entry depends only on the two entries before it, so you can keep just those two values instead of the whole table:
def fib_bottom_up(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print(fib_bottom_up(80)) # 23416728348467685
print(len(str(fib_bottom_up(5000)))) # 1045This version runs in O(n) time and uses O(1) extra space. (Python integers grow in size with their value, so the space per number is not truly constant for huge n. The count of stored values is constant.)
A Second Example: Counting Grid Paths
How many paths lead from the top-left corner of a grid to cell (r, c) if you can only move right or down? Any cell in row 0 or column 0 has exactly one path. Every other cell can be reached from above or from the left:
from functools import lru_cache
@lru_cache(maxsize=None)
def grid_paths_memo(r, c):
if r == 0 or c == 0:
return 1
return grid_paths_memo(r - 1, c) + grid_paths_memo(r, c - 1)
def grid_paths_bottom_up(rows, cols):
row = [1] * (cols + 1) # row 0: one path to every cell
for _ in range(rows):
for c in range(1, cols + 1):
row[c] += row[c - 1] # from above (old row[c]) + from left
return row[cols]
print(grid_paths_memo(2, 2)) # 6
print(grid_paths_bottom_up(2, 2)) # 6
print(grid_paths_bottom_up(10, 10)) # 184756The bottom-up version keeps a single row, updated in place. Before the update, row[c] still holds the value from the row above. After the update, row[c - 1] already holds the current row's value to the left. Getting the loop order right is the main difficulty of bottom-up code. You must compute every value before anything that depends on it.
Choosing Between the Two
| Property | Naive recursion | Memoization (top-down) | Bottom-up iteration |
|---|---|---|---|
| Time for Fibonacci | O(φⁿ), exponential | O(n) | O(n) |
| Extra space | O(n) stack | O(n) cache + O(n) stack | O(n) table, often reducible to O(1) |
| RecursionError risk | Yes | Yes, on a cold cache | No |
| Computes only needed subproblems | Yes, many times over | Yes, each once | No, computes every entry in the table |
| Effort to write | Lowest | Low: add a decorator | Higher: you must work out the loop order |
Memoization is a good choice when the recursive definition is natural, inputs are small enough for the stack, or only a sparse subset of subproblems is ever reached. Bottom-up iteration is the better choice when inputs can be large, when stack depth is a hard constraint, or when you can reduce the table to a few variables.
Exercise
A memoized function ways(n) counts ways to climb n stairs taking 1 or 2 steps at a time, with ways(0) = 1 and ways(1) = 1. Calling ways(3000) on a fresh cache raises RecursionError even though it is memoized. Explain why, and write a bottom-up version that runs in O(n) time and O(1) extra space.
Show answer
Memoization removes repeated work but not depth. On a cold cache, the first call descends through n, n - 1, ..., 1 before anything is stored, which needs about 3000 stack frames and exceeds CPython's default limit of about 1000. Bottom-up version: def ways(n): a, b = 1, 1 followed by for _ in range(n): a, b = b, a + b and then return a. Here a holds ways(i) and b holds ways(i + 1) at each step. No recursion is used, so depth is constant.
Exercise
A programmer decorates def total(items): return 0 if not items else items[0] + total(items[1:]) with @lru_cache and calls total([1, 2, 3]). What happens, and would memoization help this function even if it ran?
Show answer
It raises TypeError: unhashable type: 'list', because lru_cache uses arguments as dictionary keys and lists are not hashable. Even with a tuple argument, memoization would not help. Each call reaches a different, smaller suffix exactly once, so no subproblem repeats. Memoization pays off only when subproblems overlap. A plain loop or sum(items) is the right fix.
Exercise
In gridpathsbottom_up, what goes wrong if the inner loop runs right to left, using for c in range(cols, 0, -1)?
Show answer
row[c] += row[c - 1] would then read row[c - 1] before it has been updated for the current row, so it would add the value from the row above instead of the current row's left neighbor. After one pass, row[c] would equal 2 for every c ≥ 1 rather than c + 1, and the final counts would be wrong. The left neighbor must be computed first, so the loop must run left to right.