41- median data stream

Topic: How to get the median of a data stream?

import heapq
class GetMedian(object):
    def __init__(self):
        self.max_heap = []
        self.min_heap = []
        self.k = 0
    def insert(self,data):
        if self.k%2==0:
            x = heapq.heappushpop(self.min_heap,data)
            heapq.heappush(self.max_heap,x)
            self.k+=1
        else:
            heapq.heappush(self.min_heap,data)
            self.k += 1
    def get_median(self):
        if self.k%2:
            return heapq.nlargest(1,self.max_heap)[0]
        else:
            return (heapq.nlargest(1,self.max_heap)[0] + heapq.nsmallest(1,self.min_heap)[0])/2

NOTE: use of a large and a small roof top heap stack to achieve a small number of large storage stack top left portion, a large number of small top right part of the storage stack. When the number of insertions, if the number is even, the first smaller insert stack top, the top of the stack obtain the minimum, and then inserted into the large top stack; if the number is odd, insert the top pile small, obtaining maximum top of the stack, and then insert top small heap.

Guess you like

Origin www.cnblogs.com/kingshine007/p/11360989.html