Complete the code to calculate the value-to-weight ratio for each item.
ratio = items[i][[1]] / items[i][1]
The value is stored at index 0 in each item tuple, and weight at index 1. So ratio = value / weight = items[i][0] / items[i][1].
Complete the code to sort items by their value-to-weight ratio in descending order.
items.sort(key=lambda x: x[0] / x[[1]], reverse=True)
We sort by value/weight ratio. Weight is at index 1, so x[1].
Fix the error in the loop condition to stop when knapsack is full or all items are processed.
while W > 0 and [1] < n:
The loop index variable i tracks which item we are processing. We stop when i reaches n (total items).
Fill both blanks to add the full item value if it fits, else add fractional value.
if items[i][1] <= W: total_value += items[i][[1]] W -= items[i][[2]]
items[i][0] is value, items[i][1] is weight. We add full value and reduce capacity by full weight.
Fill all three blanks to add fractional value when item weight exceeds remaining capacity.
fraction = W / items[i][[1]] total_value += items[i][0] * [2] W -= W * [3]
Fraction is W / weight (index 1). Add value * fraction. Then W becomes zero after filling knapsack.
