Predict the output
What does this print?
import heapq
low: list[int] = [] # negated: max-heap
high: list[int] = []
out = []
for r in [5, 2, 8, 1]:
heapq.heappush(low, -r)
heapq.heappush(high, -heapq.heappop(low))
if len(high) > len(low):
heapq.heappush(low, -heapq.heappop(high))
if len(low) > len(high):
out.append(float(-low[0]))
else:
out.append((-low[0] + high[0]) / 2)
print(out)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A [5.0, 3.5, 5.0, 3.5]
Right: medians of [5], [2, 5], [2, 5, 8] and [1, 2, 5, 8].
Passing every value through the low heap first keeps all of low no bigger than all of high, so the tops are always the middle values.
Why not the others?
- B [5.0, 3.5, 5.0, 5.0]. With four readings the median is the mean of 2 and 5.
- C [5.0, 2.0, 5.0, 2.0]. Even counts average the two middle values.