From 296c30779b339a773cbe46954b0fe6ea34a19701 Mon Sep 17 00:00:00 2001 From: marina <138340846+bt3gl-cryptographer@users.noreply.github.com> Date: Wed, 2 Aug 2023 14:56:16 -0700 Subject: [PATCH] Create median_from_stream.py --- heaps/median_from_stream.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 heaps/median_from_stream.py diff --git a/heaps/median_from_stream.py b/heaps/median_from_stream.py new file mode 100644 index 0000000..34314c3 --- /dev/null +++ b/heaps/median_from_stream.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# author: bt3gl + + +class MedianFinder: + + def __init__(self): + + self.min_heap = [] + self.max_heap = [] + + + def addNum(self, num: int) -> None: + + min_heap, max_heap = self.min_heap, self.max_heap + + if len(min_heap) < len(max_heap): + heappush(min_heap, num) + + else: + heappush(max_heap, -num) + + if max_heap and min_heap and -max_heap[0] > min_heap[0]: + + heappush(max_heap, -heappop(min_heap)) + heappush(min_heap, -heappop(max_heap)) + + + def findMedian(self): + + min_heap, max_heap = self.min_heap, self.max_heap + + if len(min_heap) < len(max_heap): + return -max_heap[0] + + return (min_heap[0] - max_heap[0]) / 2