-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapsackProblem.py
More file actions
34 lines (28 loc) · 932 Bytes
/
KnapsackProblem.py
File metadata and controls
34 lines (28 loc) · 932 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
maxWeight = 50
arr = [(100, 20), (60, 10), (120, 30)]
def max(x, y):
if x > y:
return x
else:
return y
def knapsack(accCal, accWeight, toBeTried, maxCal):
if accWeight == maxWeight:
print (toBeTried)
print(accCal)
return max(accCal, maxCal)
elif len(toBeTried) == 0:
print (toBeTried)
if accWeight < maxWeight:
print (max(accCal, maxCal))
return max(accCal, maxCal)
else:
print(maxCal)
return maxCal
elif accWeight > maxWeight:
return knapsack(accCal - toBeTried[0][0], accWeight - toBeTried[0][1], toBeTried[1:], maxCal)
else:
print (toBeTried)
print(accCal)
return knapsack(accCal, accWeight, toBeTried[1:],
max(knapsack(accCal + toBeTried[0][0], accWeight + toBeTried[0][1], toBeTried[1:], maxCal), maxCal))
print(knapsack(0, 0, arr, 0))