knap

weights = [2,3,4,5]

values = [1,2,5,6]

capacity = 8

def fractional_knapsack(weights, values, capacity):

    n = len(weights)

    ratio = [(values[i] / weights[i], weights[i], values[i]) for i in range(n)]

    ratio.sort(reverse=True)

    total_value = 0

    fractions = []

    for r, w, v in ratio:

        if capacity == 0:

            break

        # Take full item if possible, else take fraction

        if w <= capacity:

            total_value += v

            fractions.append((v, w, 1))

            capacity -= w

        else:

            fraction = capacity / w

            total_value += v * fraction

            fractions.append((v, w, fraction))

            capacity = 0

    return total_value, fractions

max_value, items = fractional_knapsack(weights, values, capacity)

print(f”Maximum value in knapsack = {max_value:.2f}”)

print(“Items taken (Value, Weight, Fraction):”)

for item in items:

    print(item)