Skip to content

Commit 3ea683a

Browse files
author
Christian Bender
authored
Merge pull request #331 from bharath-123/patch-2
Thanks for contributing
2 parents 6da7bec + dc5e42a commit 3ea683a

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

Diff for: dynamic_programming/knapsack.py

+25-7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,21 @@
11
"""
22
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.
33
"""
4+
def MF_knapsack(i,wt,val,j):
5+
'''
6+
This code involves the concept of memory functions. Here we solve the subproblems which are needed
7+
unlike the below example
8+
F is a 2D array with -1s filled up
9+
'''
10+
global F # a global dp table for knapsack
11+
if F[i][j] < 0:
12+
if j < wt[i - 1]:
13+
val = MF_knapsack(i - 1,wt,val,j)
14+
else:
15+
val = max(MF_knapsack(i - 1,wt,val,j),MF_knapsack(i - 1,wt,val,j - wt[i - 1]) + val[i - 1])
16+
F[i][j] = val
17+
return F[i][j]
18+
419
def knapsack(W, wt, val, n):
520
dp = [[0 for i in range(W+1)]for j in range(n+1)]
621

@@ -12,13 +27,16 @@ def knapsack(W, wt, val, n):
1227
dp[i][w] = dp[i-1][w]
1328

1429
return dp[n][w]
15-
if __name__ == "__main__":
30+
31+
if __name__ == '__main__':
32+
'''
33+
Adding test case for knapsack
34+
'''
1635
val = [3,2,4,4]
1736
wt = [4,3,2,3]
18-
W = 6
1937
n = 4
20-
'''
21-
Should give 8
22-
'''
23-
print(knapsack(W,wt,val,n))
24-
38+
w = 6
39+
F = [[0]*(w + 1)] + [[0] + [-1 for i in range(w + 1)] for j in range(n + 1)]
40+
print(knapsack(w,wt,val,n))
41+
print(MF_knapsack(n,wt,val,w)) # switched the n and w
42+

0 commit comments

Comments
 (0)