From a9f906208016817c05f9daf660f7bd4823951c0d Mon Sep 17 00:00:00 2001 From: bharath-123 Date: Mon, 23 Jul 2018 00:36:53 +0530 Subject: [PATCH 1/2] 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. --- dynamic_programming/knapsack.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/dynamic_programming/knapsack.py b/dynamic_programming/knapsack.py index a1e4f0d80..a0b006a58 100644 --- a/dynamic_programming/knapsack.py +++ b/dynamic_programming/knapsack.py @@ -1,6 +1,21 @@ """ 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. """ +def MF_knapsack(i,wt,val,j): + ''' + This code involves the concept of memory functions. Here we solve the subproblems which are needed + unlike the below example + F is a 2D array with -1s filled up + ''' + global F # a global dp table for knapsack + if F[i][j] < 0: + if j < wt[i - 1]: + val = MF_knapsack(i - 1,wt,val,j) + else: + val = max(MF_knapsack(i - 1,wt,val,j),MF_knapsack(i - 1,wt,val,j - wt[i - 1]) + val[i - 1]) + F[i][j] = val + return F[i][j] + def knapsack(W, wt, val, n): dp = [[0 for i in range(W+1)]for j in range(n+1)] @@ -12,3 +27,16 @@ def knapsack(W, wt, val, n): dp[i][w] = dp[i-1][w] return dp[n][w] + +if name == '__main__': + ''' + Adding test case for knapsack + ''' + val = [3,2,4,4] + wt = [4,3,2,3] + n = 4 + w = 6 + F = [[0]*(w + 1)] + [[0] + [-1 for i in range(w + 1)] for j in range(n + 1)] + print(knapsack(w,wt,val,n)) + print(MF_knapsack(n,wt,val,w)) # switched the n and w + From bd7054ace9404dec5116cd858b72eb3d1cad2b16 Mon Sep 17 00:00:00 2001 From: bharath-123 Date: Mon, 23 Jul 2018 13:01:02 +0530 Subject: [PATCH 2/2] updated testcase Changed name to __name__. Sorry for the typo! --- dynamic_programming/knapsack.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dynamic_programming/knapsack.py b/dynamic_programming/knapsack.py index a0b006a58..27d1cfed7 100644 --- a/dynamic_programming/knapsack.py +++ b/dynamic_programming/knapsack.py @@ -28,7 +28,7 @@ def knapsack(W, wt, val, n): return dp[n][w] -if name == '__main__': +if __name__ == '__main__': ''' Adding test case for knapsack '''