Predict the output
What does this print?
import heapq
rocks = [-w for w in [2, 7, 4, 1, 8, 1]]
heapq.heapify(rocks)
while len(rocks) > 1:
a, b = -heapq.heappop(rocks), -heapq.heappop(rocks)
if a != b:
heapq.heappush(rocks, -(a - b))
print(-rocks[0] if rocks else 0)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 1
Right: 8-7 leaves 1, 4-2 leaves 2, 2-1 leaves 1, and 1-1 leaves the final 1.
A heap turns each 'find the two heaviest' into two O(log n) pops instead of a fresh sort.
Why not the others?
- B 0. One rock of weight 1 survives.
- C 2. The 2 left after 4-2 is later smashed against a 1.