Skip to content

Commit a9f9062

Browse files
authored
Added code for memory function implementation
Added a function which implements knapsack using memory functions. Also I updated the test cases to include test cases for the memory function implementation.
1 parent 9faaebc commit a9f9062

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Diff for: dynamic_programming/knapsack.py

+28
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,3 +27,16 @@ def knapsack(W, wt, val, n):
1227
dp[i][w] = dp[i-1][w]
1328

1429
return dp[n][w]
30+
31+
if name == '__main__':
32+
'''
33+
Adding test case for knapsack
34+
'''
35+
val = [3,2,4,4]
36+
wt = [4,3,2,3]
37+
n = 4
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)