Skip to content

Commit dd59bfb

Browse files
Fractional Knapsack
Find maximum value for given weight of knapsack or bag.
1 parent c9f4b00 commit dd59bfb

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Fractional Knapsack

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
Question: https://practice.geeksforgeeks.org/problems/fractional-knapsack/0
2+
For Explanation: Abdul Bari, GeeksForGeeks Fractional Knapsack
3+
4+
class Item:
5+
def __init__(self, weight, value, index):
6+
self.weight = weight
7+
self.value = value
8+
self.index = index
9+
self.cost = value/weight
10+
11+
def __lt__(self, other):
12+
return self.cost<other.cost
13+
14+
class FractionalKnapsack:
15+
16+
def get_max_value(self,
17+
weight,
18+
value,
19+
capacity):
20+
item_list = list()
21+
for index_ in range(len(weight)):
22+
item_list.append(Item(weight[index_],
23+
value[index_], index_))
24+
item_list.sort(reverse=True)
25+
max_value = 0
26+
for item in item_list:
27+
if item.weight<=capacity:
28+
capacity -= item.weight
29+
max_value += item.value
30+
else:
31+
# capacity -= capacity/item.weight
32+
max_value += item.value*(capacity/item.weight)
33+
break
34+
return round(max_value, 2)
35+
36+
for _ in range(int(input())):
37+
n, capacity = map(int, input().split())
38+
items_weight_val = list(map(int, input().split()))
39+
weight, value = list(), list()
40+
i = 0
41+
while i<(n*2):
42+
value.append(items_weight_val[i])
43+
weight.append(items_weight_val[i+1])
44+
i += 2
45+
fractional_knapsack = FractionalKnapsack()
46+
print(fractional_knapsack.get_max_value(weight, value, capacity))

0 commit comments

Comments
 (0)