ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
import heapq
class T:
    def __init__(self, p, n):
        self.p = p
        self.n = n
    def __lt__(self, o):
        return self.p > o.p
h = []
for p, n in [(1, 'a'), (3, 'b'), (2, 'c')]:
    heapq.heappush(h, T(p, n))
print(heapq.heappop(h).n)
  1. A. b
  2. B. a
  3. C. c
  4. D. TypeError

Correct answer: A. b

heapq only uses __lt__, and this one is reversed, so the heap is a max-heap on p. The smallest 'less-than' element is the one with the largest priority, which is b with p = 3.

More Python Programming questions

Exams that ask this topic