Sub topic 13
Memoization and Bottom-Up Iteration
This chapter assumes you have read the chapter on multiple recursion. It also assumes you know that naive Fibonacci makes an exponential number of calls, and that you can read Big-O notation. The question here is how to remove the repeated work. There are two standard answers. Memoization keeps the recursion and adds a cache. Bottom-up iteration drops the recursion and fills in answers with a loop.
Memoization: Recursion Plus a Cache
Memoization means storing the result of each call, keyed by its arguments. The function returns the stored result when the same arguments come back. Each distinct subproblem is then computed once.
Python's functools.lru_cache does this for you. Writing the cache by hand shows what the decorator is doing:
from functools import lru_cache
def fib_manual(n, cache=None):
if cache is None:
cache = {}
if n < 2:
return n
if n not in cache:
cache[n] = fib_manual(n - 1, cache) + fib_manual(n - 2, cache)
return cache[n]
@lru_cache(maxsize=None)
def fib_memo(n):
if n < 2:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
print(fib_manual(80)) # 23416728348467685
print(fib_memo(80)) # 23416728348467685With the cache, the running time drops from exponential to O(n), because there are only n + 1 distinct subproblems. The space cost is O(n) for the cache plus O(n) for the call stack. The first call still recurses all the way down to the base case before anything is stored.
Bottom-Up Iteration: Reverse the Order
Memoization works top-down. It starts at n and recurses toward the base cases. Bottom-up iteration starts at the base cases and builds upward with a loop. Because each step only needs answers that already exist, the loop needs no call stack at all.
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]
def fib_bottom_up(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print(fib_table(80)) # 23416728348467685
print(fib_bottom_up(80)) # 23416728348467685
print(len(str(fib_bottom_up(10_000)))) # 2090 digits, no RecursionErrorfib_table keeps every answer. fib_bottom_up notices that each step reads only the previous two values, so it keeps just those two. That cuts the extra space to O(1).
Comparing the Approaches
| Version | Time | Extra space | Depth risk |
|---|---|---|---|
| Naive recursion | O(φⁿ) | O(n) stack | Yes |
| Memoized recursion | O(n) | O(n) cache + O(n) stack | Yes |
| Bottom-up table | O(n) | O(n) table | No |
| Bottom-up, two variables | O(n) | O(1) | No |
Common Errors
- Unhashable arguments.
lru_cacheneeds hashable arguments, so passing a list raisesTypeError. Convert the list to a tuple first. - Mutable default cache. Writing
def f(n, cache={})shares one dictionary across all calls. That can be intentional, but it often surprises people and the cache grows without limit. - Wrong loop order. In a bottom-up loop, every value must be computed before anything reads it. If the dependencies point the other way, change the loop direction.
- Caching impure functions. If the result depends on anything besides the arguments, such as time, I/O, or global state, the cache returns stale answers.
Exercise
The number of ways to climb n stairs taking 1 or 2 steps at a time is ways(n) = ways(n-1) + ways(n-2), with ways(0) = 1 and ways(1) = 1. Write a bottom-up version that uses O(1) extra space, and say why it can handle n = 50_000 when a memoized recursive version on a fresh cache cannot.
Show answer
def ways(n): a, b = 1, 1; then loop "for _ in range(n): a, b = b, a + b"; then return a. The loop never adds stack frames, so its depth is constant. The memoized recursive version must recurse about n frames deep before its cache fills, which goes past CPython's recursion limit and raises RecursionError.
Exercise
The memoized Fibonacci runs in O(n) time. Why is its space O(n) even if you ignore the cache?
Show answer
The first call for n recurses through n-1, n-2, and so on down to the base case before any result is stored. That keeps about n frames on the call stack at the same time.