Knapsack

PHOTO EMBED

Mon Nov 18 2024 13:37:20 GMT+0000 (Coordinated Universal Time)

Saved by @badram123

class Item:
    def __init__(self, cost, weight):
        self.cost = cost
        self.weight = weight
        self.ratio = cost / weight

def fractional_knapsack(capacity, items):
    items.sort(key=lambda item: item.ratio, reverse=True)

    total_cost = 0
    for item in items:
        if capacity <= 0:
            break

        if item.weight <= capacity:
            total_cost += item.cost
            capacity -= item.weight
        else:
            total_cost += item.cost * (capacity / item.weight)
            capacity = 0

    return total_cost

if __name__ == "__main__":
    n = int(input("Enter the number of items: "))
    capacity = int(input("Enter the capacity of the knapsack: "))
    
    items = []
    for _ in range(n):
        cost, weight = map(int, input("Enter cost and weight of item (cost weight): ").split())
        items.append(Item(cost, weight))
    
    result = fractional_knapsack(capacity, items)
    print(f"The maximum cost that can be obtained: {result}")
content_copyCOPY