Sub topic 6
Top-Down Solution with Memoization
This chapter assumes you know Python functions and recursion, Big-O notation, and the 0/1 recurrence from the previous chapter:
best(i, c)is the highest value you can get from itemsionward with remaining capacityc.best(n, c) = 0.best(i, c) = max(best(i+1, c), values[i] + best(i+1, c - weights[i])). The second option is allowed only ifweights[i] <= c.
Here you turn that recurrence into working code. Then you make it fast by caching results.
Plain Recursion Repeats Work
If you translate the recurrence directly into code, each call branches twice, so the running time is O(2^n). Many of those branches end at the same state, because different sets of skipped and taken items can leave the same remaining capacity at the same index. Take weights [1, 2, 3] and capacity 5. Taking items 0 and 1 leaves capacity 2 at index 2. Skipping item 2 then reaches best(3, 2). Skipping items 0 and 1 and taking item 2 also reaches best(3, 2).
The answer to a state depends only on (i, c), not on the path that led there. So you can compute it once and store it. Storing results this way is called memoization.
The Memoized Implementation
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 answer is 220, from items 1 and 2. Greedy by value-per-weight ratio gets only 160 on this input.
The cache key is (i, c) and nothing else. values and weights come from the enclosing function, so they never need to be hashable. Each call to knapsack_memo also creates a new best with its own empty cache, so results from one input never leak into another.
Cost
| Measure | Value |
|---|---|
| Distinct states | at most (n + 1) × (W + 1) |
| Work per state | O(1) |
| Time | O(nW) |
| Cache space | O(nW) |
| Recursion depth | O(n) |
The top-down version computes only the states it can actually reach from best(0, W). When the weights are large and few in number, that can be far fewer than the full table.
Common Errors
- Putting the lists in the cache key. Writing
best(i, c, values, weights)withlru_cacheraisesTypeError: unhashable type: 'list'. Keep the data in the closure. - Caching at module level. If you decorate a top-level function that reads global data, the cache returns stale answers after the data changes. Call
best.cache_clear()or use a closure, as shown above. - Hitting the recursion limit. The depth is about n, and Python's default limit is around 1000. For a few thousand items, raise it with
sys.setrecursionlimit. Beyond that, switch to the bottom-up table in the next chapter. - Skipping the fit check. Without
weights[i] <= c, the code recurses on a negative capacity and returns invalid totals.
Exercise
For weights [1, 2, 3], values [6, 10, 12] and capacity 5, how many times is the body of best(3, 2) executed with memoization, and how many times is best(3, 2) called in total?
Show answer
The body runs once. best(3, 2) is called twice: once on the path that takes items 0 and 1 and skips item 2, and once on the path that skips items 0 and 1 and takes item 2. The second call is a cache hit. The overall answer is 22, from items 1 and 2.
Exercise
Why is (i, c) enough as the cache key, with no record of which items have already been taken?
Show answer
The best value obtainable from items i onward depends only on which items remain (those from i to n-1) and how much capacity is left. The items taken earlier affect the total only through the value already collected and through c. Neither changes the best choice among the remaining items.