Sub topic 6
Top-Down Solution with Memoization
This chapter assumes you are comfortable with Python functions and closures, recursion, and Big-O notation. It also assumes the 0/1 recurrence from the previous chapter. As a reminder, best(i, c) is the highest value you can get from items i through n - 1 with remaining capacity c:
best(n, c) = 0, because no items are left.- If
weights[i] > c, thenbest(i, c) = best(i + 1, c), because itemidoes not fit. - Otherwise,
best(i, c) = max(best(i + 1, c), values[i] + best(i + 1, c - weights[i])).
Here we turn that recurrence into working code. Then we look at why caching makes the code fast, and at the Python details that most often break it.
From recurrence to plain recursion
If you translate the recurrence word for word, you get a correct function that is far too slow:
def knapsack_naive(values, weights, capacity):
n = len(values)
def best(i, c):
if i == n:
return 0
skip = best(i + 1, c)
if weights[i] <= c:
return max(skip, values[i] + best(i + 1, c - weights[i]))
return skip
return best(0, capacity)
print(knapsack_naive([60, 100, 120], [10, 20, 30], 50)) # 220Each call can make two more calls, so in the worst case the call tree has about 2^(n+1) nodes. That is the same cost as the brute-force subset search. The recursion has done nothing more than rebuild that search as a tree.
Overlapping subproblems
Many nodes in that tree are the same subproblem. A subproblem is fully described by the pair (i, c). It does not matter which earlier items you took to get there, only how much capacity they left. Two different histories that leave the same capacity at the same item index lead to identical work.
With only three items the saving is small. When many items have similar weights, though, the same (i, c) pairs come up again and again, and plain recursion recomputes each one from scratch every time.
Adding the cache
Memoization means storing the result of each call keyed by its arguments, and returning the stored result when the same arguments come up again. Python's functools.lru_cache does this for you:
from functools import lru_cache
def knapsack_memo(values, weights, capacity):
n = len(values)
@lru_cache(maxsize=None)
def best(i, c):
if i == n:
return 0
skip = best(i + 1, c)
if weights[i] <= c:
return max(skip, values[i] + best(i + 1, c - weights[i]))
return skip
return best(0, capacity)
print(knapsack_memo([60, 100, 120], [10, 20, 30], 50)) # 220The function body is unchanged, and so is its correctness argument. The only change is the decorator. maxsize=None makes the cache unbounded, which is what you want here. A bounded LRU cache would evict states that are still needed and quietly bring back exponential behaviour.
If you prefer to see the mechanism directly, or need to inspect the table afterwards, an explicit dictionary does the same job:
def knapsack_memo_dict(values, weights, capacity):
n = len(values)
memo = {}
def best(i, c):
if i == n:
return 0
key = (i, c)
if key in memo:
return memo[key]
skip = best(i + 1, c)
if weights[i] <= c:
result = max(skip, values[i] + best(i + 1, c - weights[i]))
else:
result = skip
memo[key] = result
return result
return best(0, capacity)
print(knapsack_memo_dict([60, 100, 120], [10, 20, 30], 50)) # 220Measuring the difference
Take 20 items of weight 1 and a capacity of 20. Every item fits on every path, so plain recursion explores a full binary tree of 2^21 − 1 = 2,097,151 calls. The memoized version can report how much work it did:
from functools import lru_cache
def measure(values, weights, capacity):
n = len(values)
@lru_cache(maxsize=None)
def best(i, c):
if i == n:
return 0
skip = best(i + 1, c)
if weights[i] <= c:
return max(skip, values[i] + best(i + 1, c - weights[i]))
return skip
answer = best(0, capacity)
return answer, best.cache_info()
print(measure(list(range(1, 21)), [1] * 20, 20))
# (210, CacheInfo(hits=190, misses=231, maxsize=None, currsize=231))Only 231 distinct states are ever computed. At index i, the remaining capacity can only be one of 20 - i through 20. Every other call is a cache hit that costs O(1).
Complexity
| Quantity | Plain recursion | Memoized |
|---|---|---|
| Distinct states computed | up to 2^n paths | at most (n + 1)(W + 1) |
| Work per state | O(1) plus the recursive calls | O(1) |
| Time | O(2^n) | O(nW) |
| Extra space | O(n) call stack | O(nW) cache plus O(n) call stack |
Here W is the capacity. O(nW) is an upper bound. Top-down memoization only computes states that are reachable from (0, W). When all weights are multiples of 1,000, for example, only capacities that differ from W by a multiple of 1,000 are ever visited. That can be far fewer than the W + 1 columns a full table has to fill. This lazy evaluation is the main advantage of the top-down style over the bottom-up table in the next chapter.
Common errors and gotchas
Unhashable arguments
lru_cache uses the arguments as dictionary keys, so they must be hashable. Decorating a function that takes the lists themselves fails:
from functools import lru_cache
@lru_cache(maxsize=None)
def bad(values, weights, i, c):
return 0
try:
bad([60], [10], 0, 50)
except TypeError as e:
print(e) # unhashable type: 'list'The fix used above is to close over values and weights and pass only (i, c). You could also convert the lists to tuples, but every key would then carry the whole tuple, and each lookup would have to hash it.
Stale caches across calls
Because best is defined inside knapsack_memo, each top-level call gets a fresh cache. If you move a cached function to module level and let it read global lists, a second call with different items can return answers cached for the first instance. Keep the cache scoped to one problem instance, or call cache_clear() between instances.
Recursion depth
The call stack grows one frame per item, to a depth of n + 1. CPython's default recursion limit is 1,000, so a run with a few thousand items raises RecursionError. sys.setrecursionlimit raises the limit, but very deep recursion can then crash the interpreter by overflowing the C stack. Running the solver in a threading.Thread after calling threading.stack_size with a larger stack helps. For large n, the usual answer is the bottom-up table, which uses no recursion at all.
Memory overhead
Each cache entry is a tuple key and an integer in a hash table, which costs tens of bytes per state. A list-of-lists table costs about 8 bytes per cell. With n = 1,000 and W = 100,000 the cache can reach 10^8 entries, far beyond typical RAM. Memoization pays off when the reachable state space is sparse. When it is dense, the table is cheaper.
Exercises
Exercise
Plain recursion and the memoized version return the same answer. Why does adding lru_cache not change correctness?
Show answer
best(i, c) depends only on i and c, because the items and weights are fixed for the instance and nothing else is read. Calling it twice with the same arguments always produces the same value, so returning a stored value is equivalent to recomputing it.
Exercise
You call knapsack_memo with 5,000 items and capacity 1,000 and get a RecursionError. Name two fixes and one drawback of each.
Show answer
(1) Raise sys.setrecursionlimit. This can crash the interpreter with a C stack overflow unless you also run the solver in a thread with a larger stack via threading.stack_size. (2) Rewrite it bottom-up as a table. This removes the recursion but computes every (i, c) state, including unreachable ones.
Exercise
Weights are [1000, 2000, 3000] and the capacity is 6000. Roughly how many distinct states does the memoized version compute, compared with the (n + 1)(W + 1) cells of a full table?
Show answer
Capacities visited are always 6000 minus a multiple of 1000, so c is one of at most 7 values at each of 4 index levels. That is at most 28 states, and fewer are actually reached. A full table has 4 × 6001 = 24,004 cells.