Skip to content

Instantly share code, notes, and snippets.

@patricktrainer
Created June 15, 2023 04:01
Show Gist options
  • Save patricktrainer/7309cd2ecc08f7aa2421ada71519223c to your computer and use it in GitHub Desktop.
Save patricktrainer/7309cd2ecc08f7aa2421ada71519223c to your computer and use it in GitHub Desktop.

Revisions

  1. patricktrainer created this gist Jun 15, 2023.
    27 changes: 27 additions & 0 deletions median_calculator.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    import heapq

    class MedianCalculator:
    def __init__(self):
    self.heaps = [], []

    def add_num(self, num):
    small, large = self.heaps
    heapq.heappush(small, -heapq.heappushpop(large, num))
    if len(large) < len(small):
    heapq.heappush(large, -heapq.heappop(small))

    def find_median(self):
    small, large = self.heaps
    if len(large) > len(small):
    return float(large[0])
    return (large[0] - small[0]) / 2.0

    if __name__ == "__main__":
    median_calculator = MedianCalculator()
    try:
    while True:
    num = int(input())
    median_calculator.add_num(num)
    print('Current median: ', median_calculator.find_median())
    except EOFError:
    print('End of stream.')