Knapsack problem using Greedy technique
Algorithm:
Algorithm GreedyKnapsack(m,n)
{
for i:=1 to n do x[i] :=0.0;
U := m;
for i:= 1 to n do
{
if w[i]> U)then break;
X[i] := 1.0; U:=U-w[i];
}
if (i<=n)
then x[i] := U/w[i];
}
Source Code:
def knapsack_greedy(values, weights, capacity): n = len(values)
ratios = [(values[i] / weights[i], i) for i in range(n)]
ratios.sort(reverse=True)
selected_item=[]
total_value = 0
for ratio, i in ratios:
if weights[i] <= capacity: selected_items.append(i)
total_value += values[i] capacity -= weights[i]
return selected_items, total_value values = [10, 20, 15,
25, 30]
weights =
[5, 7, 3, 9, 2]
capacity = 15
selected_items, total_value = knapsack_greedy(values, weights,
capacity) print("Selected
items:", selected_items)
print("Total value:", total_value)
Comments
Post a Comment