ProgrammingHardCAT · MBA placement

What is printed?

What is printed?
def units(boxes, cap):
    boxes = sorted(boxes, key=lambda b: -b[1])
    total = 0
    for n, u in boxes:
        take = min(n, cap)
        total += take * u
        cap -= take
        if cap == 0:
            break
    return total
print(units([[1, 3], [2, 2], [3, 1]], 4), units([[5, 10], [2, 5]], 3))
  1. A. 8 30
  2. B. 7 30
  3. C. 8 25
  4. D. 9 30

Correct answer: A. 8 30

Boxes with more units each are loaded first, and the truck takes as many boxes as it can from each type. The first case gives 3 + 2 x 2 + 1 x 1 = 8, and the second gives 30.

More Python Programming questions

Exams that ask this topic