From be9a35429e6b1c33ab8d81ec52bef553f6075d2a Mon Sep 17 00:00:00 2001 From: yashkumarjha12 <72943344+yashkumarjha12@users.noreply.github.com> Date: Thu, 6 Oct 2022 12:00:22 +0530 Subject: [PATCH] Create Knapsack_dp.py --- Python/Knapsack_dp.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Python/Knapsack_dp.py diff --git a/Python/Knapsack_dp.py b/Python/Knapsack_dp.py new file mode 100644 index 0000000..b72fe0c --- /dev/null +++ b/Python/Knapsack_dp.py @@ -0,0 +1,20 @@ +def knapsack_dp(wt,val,W,n): + t=[[-1 for j in range(W+1)] for i in range(n+1)] + #Base Condition Initialization + for i in range(n+1): + for j in range(W+1): + if i==0 or j==0: + t[i][j] = 0 + #Recursive Case + for i in range(1,n+1): + for j in range(1,W+1): + if wt[i-1]<=W: + t[i][j] = max(val[i-1]+t[i-1][j-wt[i-1]],t[i-1][j]) + elif wt[i-1]>W: + t[i][j] = t[i-1][j] + return t[n][W] +W = 6 +wt = [1,2,3,6] +val = [1,2,4,6] +n=4 +knapsack_dp(wt,val,W,n)