-
Notifications
You must be signed in to change notification settings - Fork 0
/
Backtrack.py
43 lines (29 loc) · 1014 Bytes
/
Backtrack.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
import random
import time
def Backtrack(weights, values, length, maxValue):
if maxValue == 0 or length == 0:
return 0
if len(weights) != len(values):
return 0
if weights[length - 1] > maxValue:
return Backtrack(weights, values, length - 1, maxValue)
else:
return max(values[length - 1] + Backtrack(weights, values, length - 1, maxValue - weights[length - 1]),
Backtrack(weights, values, length - 1,
maxValue))
def printValue(value):
print("Value of items in the knapsack =", value)
capacity = 300
numOfItems = 10
weights = {}
values = {}
i = 0
for i in range(numOfItems):
weights[i] = random.randint(10, 100)
values[i] = random.randint(10, 100)
start_time = time.time()
maxValue = Backtrack(weights, values, len(values), capacity)
print("Approach BackTrack")
printValue(maxValue)
end_time = time.time()
print('time needed: ', end_time - start_time)