File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
pygorithm/dynamic_programming Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments