#3.Write a program to perform Knapsack Problem using Greedy Solution.
class Item:
def __init__(self, value, weight):
self.value = value
self.weight = weight
def value_density(self):
return self.value / self.weight
def knapsack_greedy(items, capacity):
items.sort(key=lambda item: item.value_density(), 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.value_density() * capacity
break
return total_value
# Example usage
items = [
Item(60, 10),
Item(100, 20),
Item(120, 30)
]
capacity = 50
max_value = knapsack_greedy(items, capacity)
print(f"Maximum value in knapsack = {max_value}")