Skip to content

Commit a0b55ed

Browse files
[new] added 0/1 knapsack python code
1 parent 283f464 commit a0b55ed

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# This is the memoization approach of 0 / 1 Knapsack in Python in simple
2+
# Method : Dynamic Programming
3+
# Author : Neeraj Pratap Hazarika
4+
5+
# Problem Statement : Given a set of items, each with a weight and a value, take items to include in a knapsack such that the total weight is less than or equal to a given limit and the total value is as large as possible. Print the total value.
6+
7+
# ------------------------------------------------------------
8+
9+
# declare universal scope 2d matrix, dp
10+
dp=[[]]
11+
12+
def knapsack(wt, val, W, n):
13+
14+
# base conditions
15+
if n == 0 or W == 0:
16+
return 0
17+
if dp[n][W] != -1:
18+
return dp[n][W]
19+
20+
# choice diagram code
21+
if wt[n-1] <= W:
22+
dp[n][W] = max(val[n-1] + knapsack(wt, val, W-wt[n-1], n-1), knapsack(wt, val, W, n-1))
23+
return dp[n][W]
24+
elif wt[n-1] > W:
25+
dp[n][W] = knapsack(wt, val, W, n-1)
26+
return dp[n][W]
27+
28+
# Driver code
29+
if __name__ == '__main__':
30+
# Inputs
31+
W = int(input("Enter the maximum weight the knapsack can hold : "))
32+
n = int(input("Enter number of items to be choosen from : "))
33+
print("Enter the weights to be choosen from : ")
34+
wt = list(map(int,input().strip().split()))[:n]
35+
print("Enter the values corresponding to these weights : ")
36+
val = list(map(int,input().strip().split()))[:n]
37+
38+
# Initialize 2d matrix, dp
39+
dp = [[-1 for i in range(W + 1)] for j in range(n + 1)]
40+
41+
print("Maximum profit : ",knapsack(wt, val, W, n))
42+
43+
# ------------------------------------------------------------
44+
45+
# Inputs given :
46+
# Enter the maximum weight the knapsack can hold : 50
47+
# Enter number of items to be choosen from : 3
48+
# Enter the weights to be choosen from :
49+
# 10 20 30
50+
# Enter the values corresponding to these weights :
51+
# 60 100 120
52+
53+
# Output :
54+
# Maximum profit : 220

0 commit comments

Comments
 (0)