1
1
"""
2
2
Given weights and values of n items, put these items in a knapsack of
3
- capacity W to get the maximum total value in the knapsack.
3
+ capacity W to get the maximum total value in the knapsack.
4
4
5
5
Note that only the integer weights 0-1 knapsack problem is solvable
6
- using dynamic programming.
6
+ using dynamic programming.
7
7
"""
8
8
9
9
@@ -27,7 +27,7 @@ def mf_knapsack(i, wt, val, j):
27
27
28
28
29
29
def knapsack (w , wt , val , n ):
30
- dp = [[0 for i in range (w + 1 )] for j in range (n + 1 )]
30
+ dp = [[0 for _ in range (w + 1 )] for _ in range (n + 1 )]
31
31
32
32
for i in range (1 , n + 1 ):
33
33
for w_ in range (1 , w + 1 ):
@@ -108,7 +108,7 @@ def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set):
108
108
dp: list of list, the table of a solved integer weight dynamic programming problem
109
109
110
110
wt: list or tuple, the vector of weights of the items
111
- i: int, the index of the item under consideration
111
+ i: int, the index of the item under consideration
112
112
j: int, the current possible maximum weight
113
113
optimal_set: set, the optimal subset so far. This gets modified by the function.
114
114
@@ -136,7 +136,7 @@ def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set):
136
136
wt = [4 , 3 , 2 , 3 ]
137
137
n = 4
138
138
w = 6
139
- f = [[0 ] * (w + 1 )] + [[0 ] + [- 1 for i in range (w + 1 )] for j in range (n + 1 )]
139
+ f = [[0 ] * (w + 1 )] + [[0 ] + [- 1 for _ in range (w + 1 )] for _ in range (n + 1 )]
140
140
optimal_solution , _ = knapsack (w , wt , val , n )
141
141
print (optimal_solution )
142
142
print (mf_knapsack (n , wt , val , w )) # switched the n and w
0 commit comments