Skip to content

Commit bec27f5

Browse files
Create Enhancement of the knapsack algorithm TheAlgorithms#9266
1 parent 4f2a046 commit bec27f5

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

Diff for: Enhancement of the knapsack algorithm #9266

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
The following is a Python implementation of the 0-1 knapsack problem with memorization:
2+
3+
def knapsack_memorization(weights, values, capacity):
4+
"""Solves the 0-1 knapsack problem using memorization.
5+
6+
Args:
7+
weights: A list of weights of the items.
8+
values: A list of values of the items.
9+
capacity: The capacity of the knapsack.
10+
11+
Returns:
12+
The maximum value of the items that can be placed in the knapsack.
13+
"""
14+
15+
memo = {}
16+
17+
def knapsack_helper(i, capacity):
18+
if i == 0 or capacity == 0:
19+
return 0
20+
21+
key = (i, capacity)
22+
if key in memo:
23+
return memo[key]
24+
25+
if weights[i - 1] > capacity:
26+
max_value = knapsack_helper(i - 1, capacity)
27+
else:
28+
max_value = max(knapsack_helper(i - 1, capacity),
29+
values[i - 1] + knapsack_helper(i - 1, capacity - weights[i - 1]))
30+
31+
memo[key] = max_value
32+
return max_value
33+
34+
return knapsack_helper(len(weights), capacity)
35+
36+
37+
38+
The following is a Python implementation of the 0-N knapsack problem:
39+
40+
def knapsack_0_n(weights, values, capacity):
41+
"""Solves the 0-N knapsack problem.
42+
43+
Args:
44+
weights: A list of weights of the items.
45+
values: A list of values of the items.
46+
capacity: The capacity of the knapsack.
47+
48+
Returns:
49+
The maximum value of the items that can be placed in the knapsack.
50+
"""
51+
52+
memo = {}
53+
54+
def knapsack_helper(i, capacity):
55+
if i == 0 or capacity == 0:
56+
return 0
57+
58+
key = (i, capacity)
59+
if key in memo:
60+
return memo[key]
61+
62+
max_value = 0
63+
for j in range(1, capacity // weights[i - 1] + 1):
64+
max_value = max(max_value, values[i - 1] * j + knapsack_helper(i - 1, capacity - weights[i - 1] * j))
65+
66+
memo[key] = max_value
67+
return max_value
68+
69+
return knapsack_helper(len(weights), capacity)
70+

0 commit comments

Comments
 (0)