Skip to content

Commit e2a83b3

Browse files
creatornadirancclausspre-commit-ci[bot]
authored
Update knapsack.py (#7271)
* Update knapsack.py * Update dynamic_programming/knapsack.py Co-authored-by: Christian Clauss <[email protected]> * Update knapsack.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: Christian Clauss <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 39a99b4 commit e2a83b3

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

dynamic_programming/knapsack.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
"""
22
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.
44
55
Note that only the integer weights 0-1 knapsack problem is solvable
6-
using dynamic programming.
6+
using dynamic programming.
77
"""
88

99

@@ -27,7 +27,7 @@ def mf_knapsack(i, wt, val, j):
2727

2828

2929
def knapsack(w, wt, val, n):
30-
dp = [[0 for i in range(w + 1)] for j in range(n + 1)]
30+
dp = [[0] * (w + 1) for _ in range(n + 1)]
3131

3232
for i in range(1, n + 1):
3333
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):
108108
dp: list of list, the table of a solved integer weight dynamic programming problem
109109
110110
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
112112
j: int, the current possible maximum weight
113113
optimal_set: set, the optimal subset so far. This gets modified by the function.
114114
@@ -136,7 +136,7 @@ def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set):
136136
wt = [4, 3, 2, 3]
137137
n = 4
138138
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] * (w + 1) for _ in range(n + 1)]
140140
optimal_solution, _ = knapsack(w, wt, val, n)
141141
print(optimal_solution)
142142
print(mf_knapsack(n, wt, val, w)) # switched the n and w

0 commit comments

Comments
 (0)