ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
import heapq
h = []
for x in [4, 9, 1, 7]:
    heapq.heappush(h, -x)
print(-heapq.heappop(h), -h[0])
  1. A. 1 7
  2. B. 9 9
  3. C. 9 7
  4. D. 9 4

Correct answer: C. 9 7

Pushing negated values turns the min-heap into a max-heap. The first pop gives -9, so the largest value is 9. The new top after the pop is -7, so h[0] negated is 7.

More Python Programming questions

Exams that ask this topic