Created
June 15, 2023 04:01
-
-
Save patricktrainer/7309cd2ecc08f7aa2421ada71519223c to your computer and use it in GitHub Desktop.
Revisions
-
patricktrainer created this gist
Jun 15, 2023 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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.')