Advertisement
rishu110067

Untitled

Feb 9th, 2022
770
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. import heapq
  2.  
  3. def online_median(stream):
  4.  
  5.     min_heap = []
  6.     max_heap = []
  7.     results = []
  8.  
  9.     for i in stream:
  10.         # Mainly we want to keep the min and max heap balanced
  11.         # We want to make sure the max heap is always negative numbers so we have reverse of min heap
  12.         # Below - we push the i into min heap
  13.         # Then we pop the smallest item out of the min heap
  14.         # Then we pop the smallest item from the min heap on to the max heap
  15.         # import pdb; pdb.set_trace();
  16.         heapq.heappush(max_heap, -heapq.heappushpop(min_heap,i))
  17.         # The length of max heap should always be equal or greater than min heap
  18.         # In case of streamed count to be off, min heap will give the median
  19.         # In case of even count, min and max together will give the median
  20.         # Below - we ppop the element out of mac heap and push it min heap when the len of max_heap is greater than min_heap
  21.         if len(max_heap) > len(min_heap):
  22.             heapq.heappush(min_heap, -heapq.heappop(max_heap))
  23.        
  24.         #print(i)
  25.         # append the results of the emdian stream
  26.         results.append((min_heap[0] - max_heap[0])//2 if len(max_heap) == len(min_heap) else min_heap[0])
  27.  
  28.     return results
  29.  
  30. # test1
  31. # test1 = [7,8,1,23,4]
  32. # print(online_median(test1))
  33.  
  34. # test2
  35. # test2 = [1,2,3,4,5]
  36. # print(online_median(test2))
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement