Use descending capacity for 0/1 knapsack
Each item may be chosen once. A one-dimensional table stores the best value available at every capacity. Updating capacities from high to low is essential: it makes each transition read the previous item set. Updating upward would reuse the same item repeatedly and solve a different problem.
best = [0, 0, 0, 0]
for capacity in range(3, 1, -1):
best[capacity] = 5
print(best)Think before coding
Descending updates prevent the current item from appearing in the state used to add it. Skipping and taking cover all valid choices. Complexity is the number of items times the capacity. Work through the example by hand before changing the starter. Decide what should happen for an empty input, a single value and a repeated value where those cases apply. The checks use several inputs so a hard-coded answer cannot stand in for the rule.
Your task
Write pack(items, capacity). Each item is a (positive_weight, nonnegative_value) pair. Return the greatest total value whose weight fits capacity, choosing each item at most once.
The explanation opens here once every check passes.