Skip to content

Commit 301df8b

Browse files
authored
0-1 Knapsack python code added
1 parent e442c6a commit 301df8b

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

DP/Knapsack/0-1Knapsack.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Returns the maximum value that can be put in a knapsack of
2+
# capacity W
3+
def knapSack(W , wt , val , n):
4+
5+
# Base Case
6+
if n == 0 or W == 0 :
7+
return 0
8+
9+
# If weight of the nth item is more than Knapsack of capacity
10+
# W, then this item cannot be included in the optimal solution
11+
if (wt[n-1] > W):
12+
return knapSack(W , wt , val , n-1)
13+
14+
# return the maximum of two cases:
15+
# (1) nth item included
16+
# (2) not included
17+
else:
18+
return max(val[n-1] + knapSack(W-wt[n-1] , wt , val , n-1),
19+
knapSack(W , wt , val , n-1))
20+
21+
# end of function knapSack
22+
23+
# To test above function
24+
val = [60, 100, 120]
25+
wt = [10, 20, 30]
26+
W = 50
27+
n = len(val)
28+
print knapSack(W , wt , val , n)

0 commit comments

Comments
 (0)