ProgrammingHardCognizant GenC · TCS NQT

What is printed?

What is printed?
import heapq, itertools
c = itertools.count()
h = []
for p, name in [(2, 'x'), (1, 'y'), (2, 'z'), (1, 'w')]:
    heapq.heappush(h, (p, next(c), name))
print([heapq.heappop(h)[2] for _ in range(4)])
  1. A. ['y', 'w', 'z', 'x']
  2. B. ['y', 'w', 'x', 'z']
  3. C. ['w', 'y', 'x', 'z']
  4. D. ['x', 'y', 'w', 'z']

Correct answer: B. ['y', 'w', 'x', 'z']

The counter gives each item an insertion number that breaks ties, so among priority 1 y comes before w, and among priority 2 x comes before z.

More Python Programming questions

Exams that ask this topic