Knapsack 01 Dynamic Programming (Python)
Solve the 0-1 knapsack problem using dynamic programming with a one dimensional rolling array.
Code
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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.