0% found this document useful (0 votes)
4 views1 page

Knapsack Algorithm

The document contains a Python implementation of a greedy algorithm for the knapsack problem. It calculates the maximum value that can be carried in a knapsack given weights and values of items, while allowing fractional items. The user inputs the number of items, their weights, values, and the knapsack's capacity to obtain the result.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

Knapsack Algorithm

The document contains a Python implementation of a greedy algorithm for the knapsack problem. It calculates the maximum value that can be carried in a knapsack given weights and values of items, while allowing fractional items. The user inputs the number of items, their weights, values, and the knapsack's capacity to obtain the result.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

def knapsack_greedy(weights, values, capacity):

n = len(weights)
items = [(values[i] / weights[i], weights[i], values[i]) for i in range(n)]
#Sortby value-to-weight ra o in descending order
items.sort(reverse=True, key=lambda x: x[0])
total_value = 0
knapsack = []
for ra o, weight, value in items:
if capacity >= weight:
knapsack.append((weight, value))
total_value += value
capacity -= weight
else:
frac on = capacity / weight
knapsack.append((weight * frac on, value * frac on))
total_value += value * frac on
break
return total_value, knapsack
n = int(input("Enter number of items: "))
weights = []
values = []
for i in range(n):
weight = float(input(f"Enter weight of item {i + 1}: "))
value = float(input(f"Enter value of item {i + 1}: "))
weights.append(weight)
values.append(value)
capacity = float(input("Enter knapsack capacity: "))
total_value, knapsack = knapsack_greedy(weights, values, capacity)
print(f"\nMaximum value possible: {total_value}")
print("Items taken (weight, value):")
for weight, value in knapsack:
print(f"({weight:.2f}, {value:.2f})")

Output:

You might also like