NEP -DAA -DESIGN AND ANALYSIS OF ALOGRITHM

PROGRAM 1 PROGRAM 2 PROGRAM 3 PROGRAM 4 PROGRAM 5 PROGRAM 6 PROGRAM 7 PROGRAM 8 PROGRAM 9 PROGRAM 10 PROGRAM 11 PROGRAM 12

PART B

PROGRAM B1 PROGRAM B2 PROGRAM B3 PROGRAM B4 PROGRAM B5 PROGRAM B6 PROGRAM B7 PROGRAM B8 . . .

3

 
  
 #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}")