Skip to content

Commit 5e828fc

Browse files
some pep8 cleanup too
1 parent 47f76eb commit 5e828fc

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

dynamic_programming/knapsack.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,25 @@
11
"""
2-
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack.
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.
34
4-
Note that only the integer weights 0-1 knapsack problem is solvable using dynamic programming.
5+
Note that only the integer weights 0-1 knapsack problem is solvable
6+
using dynamic programming.
57
"""
68

7-
def MF_knapsack(i,wt,val,j):
9+
10+
def MF_knapsack(i, wt, val, j):
811
'''
912
This code involves the concept of memory functions. Here we solve the subproblems which are needed
1013
unlike the below example
1114
F is a 2D array with -1s filled up
1215
'''
1316
global F # a global dp table for knapsack
1417
if F[i][j] < 0:
15-
if j < wt[i - 1]:
16-
val = MF_knapsack(i - 1,wt,val,j)
18+
if j < wt[i-1]:
19+
val = MF_knapsack(i-1, wt, val, j)
1720
else:
18-
val = max(MF_knapsack(i - 1,wt,val,j),MF_knapsack(i - 1,wt,val,j - wt[i - 1]) + val[i - 1])
21+
val = max(MF_knapsack(i-1, wt, val, j),
22+
MF_knapsack(i-1, wt, val, j - wt[i-1]) + val[i-1])
1923
F[i][j] = val
2024
return F[i][j]
2125

@@ -24,9 +28,9 @@ def knapsack(W, wt, val, n):
2428
dp = [[0 for i in range(W+1)]for j in range(n+1)]
2529

2630
for i in range(1,n+1):
27-
for w in range(1,W+1):
28-
if(wt[i-1]<=w):
29-
dp[i][w] = max(val[i-1]+dp[i-1][w-wt[i-1]],dp[i-1][w])
31+
for w in range(1, W+1):
32+
if wt[i-1] <= w:
33+
dp[i][w] = max(val[i-1] + dp[i-1][w-wt[i-1]], dp[i-1][w])
3034
else:
3135
dp[i][w] = dp[i-1][w]
3236

0 commit comments

Comments
 (0)