-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathknapsackProblem.py
More file actions
42 lines (32 loc) · 888 Bytes
/
knapsackProblem.py
File metadata and controls
42 lines (32 loc) · 888 Bytes
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
class Sack:
def __init__(self, wt, val):
self.wt = wt
self.val = val
self.cost = val // wt
def __lt__(self, other):
return self.cost < other.cost
def knapsack(wt, val, W):
item = []
for i in range(len(wt)):
item.append(Sack(wt[i], val[i]))
item.sort(reverse=True)
totalValue = 0
for i in range(len(item)):
curWt = item[i].wt
curVal = item[i].val
if W - curWt >= 0:
W -= curWt
totalValue += curVal
else:
fraction = W / curWt
totalValue += curVal * fraction
W = int(W - (curWt * fraction))
break
return totalValue
def main():
wt = [10, 40, 20, 30]
val = [60, 40, 100, 120]
W = 50
print(knapsack(wt, val, W))
if __name__ == "__main__":
main()