fractional knapsack
Wed Nov 06 2024 16:41:52 GMT+0000 (Coordinated Universal Time)
Saved by
@sagar123
class Item:
def __init__(self, value, weight):
self.value = value
self.weight = weight
self.ratio = value / weight
def fractional_knapsack(items, capacity):
items.sort(key=lambda item: item.ratio, reverse=True)
total_value = 0.0
for item in items:
if capacity >= item.weight:
capacity -= item.weight
total_value += item.value
else:
total_value += item.ratio * capacity
break
return total_value
n = int(input("Enter the number of items: "))
items = []
for i in range(n):
value = float(input(f"Enter value of item {i+1}: "))
weight = float(input(f"Enter weight of item {i+1}: "))
items.append(Item(value, weight))
capacity = float(input("Enter the capacity of the knapsack: "))
max_value = fractional_knapsack(items, capacity)
print(f"Maximum value in the knapsack: {max_value}")
content_copyCOPY
Comments