ProgrammingVery hardInfosys HackWithInfy · TCS CodeVita

What is printed?

What is printed?
import heapq
def medians(xs):
    lo, hi = [], []
    out = []
    for x in xs:
        heapq.heappush(lo, -x)
        heapq.heappush(hi, -heapq.heappop(lo))
        if len(hi) > len(lo):
            heapq.heappush(lo, -heapq.heappop(hi))
        out.append(-lo[0] if len(lo) > len(hi) else (-lo[0] + hi[0]) / 2)
    return out
print(medians([5, 15, 1, 3]))
  1. A. [5, 10, 5, 4]
  2. B. [5, 10.0, 5, 3.0]
  3. C. [5, 10.0, 5, 4]
  4. D. [5, 10.0, 5, 4.0]

Correct answer: D. [5, 10.0, 5, 4.0]

Two heaps keep the lower half in a max-heap and the upper half in a min-heap. Dividing by 2 in Python 3 gives a float, so the even-count medians print as 10.0 and 4.0.

More Python Programming questions

Exams that ask this topic