Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

How to efficiently create a median finder for a stream of values, in Python?

"""
The median is the middle value of an ordered list 
of elements. If the elements count is even, then
the median is the average of the two middle elements.

For instance, in [3, 4, 5], median = 4, while
in [3, 4], median = (3+4)/2 = 3.5.

The below implementation creates a MedianFinder
class that streamlines the process of finding the median
for a stream of n values. 

Space complexity: O(n), to hold the values in heaps.
"""
from heapq import heappop, heappush

class median_finder:
    # Time complexity: O(1)
    def __init__(self):
        self.los = []
        self.his = []
        self.median = 0
    # Time complexity: O(log2(n))
    def add_num(self, num):
        if len(self.los) == 0 or (-1*self.los[0]) > num:
            heappush(self.los, -1*num)
        else:
            heappush(self.his, num)
        self.rebalance_his_los()
        self.update_median()
    # Time complexity: O(log2(n))
    def rebalance_his_los(self):
        los_length = len(self.los)
        his_length = len(self.his)
        if los_length - his_length == 2:
            heappush(self.his, -1*heappop(self.los))
        elif his_length - los_length == 2:
            heappush(self.los, -1*heappop(self.his))
    # Time complexity: O(1)
    def update_median(self):
        los_length = len(self.los)
        his_length = len(self.his)
        if los_length == his_length:
            self.median = (-1*self.los[0] + self.his[0])/2
        elif los_length > his_length:
            self.median = -1*self.los[0]
        else:
            self.median = self.his[0]
    # Time complexity: O(1)
    def find_median(self):
        return self.median

median_finder_obj1 = median_finder()
median_finder_obj1.add_num(3)
median_finder_obj1.add_num(4)
median_finder_obj1.add_num(5)
print("Median:", median_finder_obj1.find_median())  # Median: 4
median_finder_obj2 = median_finder()
median_finder_obj2.add_num(3)
median_finder_obj2.add_num(4)
print("Median:", median_finder_obj2.find_median())  # Median: 3.5
Comment

PREVIOUS NEXT
Code Example
Python :: how to import PyMem python 
Python :: array comparison in percent 
Python :: get package share vs FindPackageShare 
Python :: pandas select column by index 
Python :: how to install django in virtual environment in ubuntu 
Python :: python milliseconds to date 
Python :: how to write in google chrome console in python 
Python :: get all indices of a value in list python 
Python :: load csv file using pandas 
Python :: python replace newline 
Python :: check if env variable exists python 
Python :: python hex to bytes string 
Python :: how to make a tick update in python 
Python :: pt_core_news_sm spacy download 
Python :: dataframe unique values in each column 
Python :: how to set interval in python 
Python :: numpy round 
Python :: get dictionary in array python by value 
Python :: pyqt5 qtwebenginewidgets not found 
Python :: matplotlib title cilpped off 
Python :: python join list of strings with separator 
Python :: python compare two json objects and get difference 
Python :: utc to local time python 
Python :: how to convert 24 hours to 12 hours in python 
Python :: python split dict into chunks 
Python :: count the frequency of words in a file 
Python :: python write csv line by line 
Python :: convert letters to numbers in python 
Python :: django gunicorn static file not found 
Python :: django import timezone 
ADD CONTENT
Topic
Content
Source link
Name
5+5 =