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

Popular posts from this blog

2. Create 3 private networks namely N1, N2 and N3, Send the data from N1 to N2. If the packets are transferring from N3, it shouldn't accept the packets. Accordingly develop the security features.Create 3 private networks namely N1, N2 and N3, Send the data from N1 to N2. If the packets are transferring from N3, it shouldn't accept the packets. Accordingly develop the security features.

Kruskal algorithm using greedy technique.