Skip to content

Commit 1d35bfe

Browse files
committed
Added binary knapsack implementation using dynamic programming
1 parent 68f28b3 commit 1d35bfe

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'''
2+
Author: Omkar Pathak
3+
Created At: 25th August 2017
4+
'''
5+
6+
def knapsack(W, value, weight, n):
7+
'''
8+
:param W: maximum weight capacity
9+
:param value: an array of values of items in the knapsack
10+
:param weight: an array of weights of items in the knapsack
11+
:param n: number of items in the knapsack
12+
'''
13+
knap_sack = [[0 for x in range(W+1)] for x in range(n+1)]
14+
15+
for j in range(W + 1):
16+
knap_sack[0][j] = 0
17+
18+
for i in range(n + 1):
19+
for w in range(W + 1):
20+
if weight[i - 1] <= w:
21+
knap_sack[i][w] = max(value[i - 1] + knap_sack[i - 1][w - weight[i - 1]], knap_sack[i - 1][w])
22+
else:
23+
knap_sack[i][w] = knap_sack[i - 1][w]
24+
25+
return knap_sack[n][w]
26+
27+
28+
def get_code():
29+
"""
30+
returns the code for the knapsack function
31+
"""
32+
return inspect.getsource(knapsack)

0 commit comments

Comments
 (0)