-
Notifications
You must be signed in to change notification settings - Fork 0
/
Greedy.py
50 lines (36 loc) · 1.1 KB
/
Greedy.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
import random
import time
def greedyKnapsack(Capacity, values, weights, Ratio):
knapsack = []
Weight = 0
Value = 0
while (Weight <= Capacity):
maxItem = max(Ratio)
indexOfMaxItem = Ratio.index(maxItem)
if weights[indexOfMaxItem] + Weight <= Capacity:
knapsack.append(indexOfMaxItem + 1)
Weight += weights[indexOfMaxItem]
Value += values[indexOfMaxItem]
Ratio[indexOfMaxItem] = -1
else:
break
return Value
def printValue(value):
print("Value of items in the knapsack =", value)
Capacity = 300
numOfItems = 1000
weights = {}
values = {}
i = 0
for i in range(numOfItems):
weights[i] = random.randint(10, 100)
values[i] = random.randint(10, 100)
Ratio = []
for index in range(numOfItems):
Ratio.append(values[index] / weights[index])
print("\nGreedy Approach")
start_time = time.time()
maxValue = greedyKnapsack(Capacity, values, weights, Ratio)
printValue(maxValue)
end_time = time.time()
print('time needed: ', end_time - start_time)