It has nothing to do with scope. Heaps do not grow because you added new elements at the end:
return (heapq.heappop(leftHeap) + curMedian)/2
else:
return (heapq.heappop(rightHeap) + curMedian)/2
Just look at the max / min element without unloading it:
return (leftHeap[0] + curMedian)/2
else:
return (rightHeap[0] + curMedian)/2
My own version I mentioned in the comments:
from heapq import heappush, heappop
left, right = [], []
def runmed(n):
global left, right
if len(left) <= len(right):
heappush(left, -n)
else:
heappush(right, n)
if right and -left[0] > right[0]:
heappush(left, -heappop(right))
heappush(right, -heappop(left))
if len(left) > len(right):
return -left[0]
return (right[0] - left[0]) / 2.0
left - This is the maximum heap of less than half of the numbers and contains those numbers that were nullified to get max-heap functionality.right - - .left , right, .
:
import random
numbers = []
for _ in range(15):
n = random.randrange(100)
numbers.append(n)
print '{:<4} is median of {}'.format(runmed(n), sorted(numbers))
:
38 is median of [38]
27.5 is median of [17, 38]
38 is median of [17, 38, 79]
27.5 is median of [4, 17, 38, 79]
17 is median of [4, 12, 17, 38, 79]
27.5 is median of [4, 12, 17, 38, 63, 79]
38 is median of [4, 12, 17, 38, 63, 69, 79]
35.0 is median of [4, 12, 17, 32, 38, 63, 69, 79]
38 is median of [4, 12, 17, 32, 38, 39, 63, 69, 79]
38.5 is median of [4, 12, 17, 32, 38, 39, 63, 69, 79, 82]
39 is median of [4, 12, 17, 32, 38, 39, 47, 63, 69, 79, 82]
38.5 is median of [4, 12, 17, 21, 32, 38, 39, 47, 63, 69, 79, 82]
38 is median of [4, 12, 17, 21, 25, 32, 38, 39, 47, 63, 69, 79, 82]
35.0 is median of [4, 12, 14, 17, 21, 25, 32, 38, 39, 47, 63, 69, 79, 82]
38 is median of [4, 12, 14, 17, 21, 25, 32, 38, 39, 47, 62, 63, 69, 79, 82]