ProgrammingVery hardCAT · MBA placement

What is printed?

What is printed?
items = [(60, 10), (100, 20), (120, 30)]
cap = 50
best = 0
w = 0
for v, wt in sorted(items, key=lambda x: x[0] / x[1], reverse=True):
    if w + wt <= cap:
        w += wt
        best += v
print(best)
  1. A. 220
  2. B. 180
  3. C. 240
  4. D. 160

Correct answer: D. 160

Greedy by value per weight takes the 60 and 100 items, which weigh 30. The 120 item then does not fit in the remaining 20, so the total is 160; the optimal pair 100 and 120 gives 220.

More Python Programming questions

Exams that ask this topic