-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathknapsack.py
93 lines (28 loc) · 1.11 KB
/
knapsack.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class Myclass(object):
def __init__(self, value, table):
self.value = value
self.table = table
def knapsack(W, val, wgh, n):
K = [[Myclass(0,[False for x in range(n)]) for x in range(W+1)] for y in range(n+1)]
for i in range(n+1):
for w in range(W+1):
if i == 0 or w == 0:
K[i][w].value = 0
K[i][w].table = [False for x in range(n)]
elif wgh[i-1] > w:
K[i][w] = K[i-1][w]
else:
if val[i-1] + K[i-1][w-wgh[i-1]].value > K[i-1][w].value:
K[i][w].value = val[i-1] + K[i-1][w-wgh[i-1]].value
K[i][w].table = K[i-1][w-wgh[i-1]].table
K[i][w].table[i-1] = True
else:
K[i][w] = K[i-1][w]
return K[n][W]
val = [60, 100, 120]
wgh = [10, 20, 30]
W = 50
n = len(val)
result = knapsack(W, val, wgh, n)
print(result.value)
print(result.table)