Two Heap Running Median
Split a value stream across two heapq heaps so every insert rebalances the halves and yields the exact running median without re-sorting.
Code
import heapq
def running_median(values):
"""Yield the exact median after each insert using two heaps."""
small = [] # negated max-heap: the smaller half
large = [] # min-heap: the larger half
for value in values:
heapq.heappush(small, -value)
# move the largest of the small half over to the large half
heapq.heappush(large, -heapq.heappop(small))
# rebalance so small holds equal or exactly one more item
if len(large) > len(small):
heapq.heappush(small, -heapq.heappop(large))
if len(small) > len(large):
median = -small[0]
else:
median = (-small[0] + large[0]) / 2
yield median
for count, median in enumerate(running_median([5, 1, 9, 3, 7]), start=1):
print(f"count={count} median={median}")Output
Captured from a sandboxed run of this snippet in the build pipeline.
count=1 median=5
count=2 median=3.0
count=3 median=5
count=4 median=4.0
count=5 median=5What the code does
Two Heap Running Median is built around the function running_median.
The loop for value in values is the only repeated construct.
Watch out for
- Each symbol it names is a language built-in — nothing to download.
Applying it
The entry-point signature is def running_median(values)
The run emits 1 labeled section — count= — one per step.
Callers only need running_median — everything else stays internal.
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `running_median` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.