ProgrammingVery hardProduct company OA

What is printed?

What is printed?
import heapq
tasks = [(2, "write"), (1, "test"), (2, "ship"), (1, "plan")]
h = []
for i, (p, name) in enumerate(tasks):
    heapq.heappush(h, (p, -i, name))
order = [heapq.heappop(h)[2] for _ in range(3)]
print(order, h[0][2], heapq.nsmallest(2, tasks)[1])
  1. A. ['test', 'plan', 'write'] ship (1, 'test')
  2. B. ['plan', 'test', 'write'] ship (1, 'test')
  3. C. ['plan', 'test', 'ship'] write (2, 'ship')
  4. D. ['plan', 'test', 'ship'] write (1, 'test')

Correct answer: D. ['plan', 'test', 'ship'] write (1, 'test')

Tuples compare element by element, so among equal priorities the second field decides. It is −i, which makes the LATER-inserted task smaller: (1, −3, plan) < (1, −1, test) < (2, −2, ship) < (2, 0, write). Three pops give plan, test, ship and 'write' remains. nsmallest on the raw (priority, name) tuples breaks the tie alphabetically: (1, 'plan'), (1, 'test'). Using +i as the tie-breaker would give the FIFO order test, plan, write.

More Python Programming questions

Exams that ask this topic