Knapsack 01 Dynamic Programming (Python)

Solve the 0-1 knapsack problem using dynamic programming with a one dimensional rolling array.

PythonData Integrity

Code

pythonsnippet
11 lines
def knapsack01(weights, values, capacity):
    n = len(weights)
    dp = [0] * (capacity + 1)
    for i in range(n):
        next_dp = [0] * (capacity + 1)
        for w in range(capacity + 1):
            next_dp[w] = dp[w]
            if w >= weights[i] and dp[w - weights[i]] + values[i] > next_dp[w]:
                next_dp[w] = dp[w - weights[i]] + values[i]
        dp = next_dp
    return dp[capacity]

What the program does next

Knapsack 01 Dynamic Programming (Python) keeps everything in the function knapsack01.

Iteration happens inside for i in range(n) — everything outside it runs once.

Putting it to use

The main signature reads def knapsack01(weights, values, capacity)

knapsack01 is what another module would consume; nothing else here is load-bearing for callers.

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `knapsack01` at load time.