Find the Running Median

  • + 0 comments

    Python3

    import heapq import sys

    def runningMedian(a):

    lower_half = []   
    upper_half = []   
    
    result = []
    
    for num in a:
    
        if len(lower_half) == 0 or num <= -lower_half[0]:
            heapq.heappush(lower_half, -num)  
        else:
            heapq.heappush(upper_half, num)
    
    
        if len(lower_half) > len(upper_half) + 1:
            moved_item = -heapq.heappop(lower_half)
            heapq.heappush(upper_half, moved_item)
        elif len(upper_half) > len(lower_half):
            moved_item = heapq.heappop(upper_half)
            heapq.heappush(lower_half, -moved_item)
    
        if len(lower_half) == len(upper_half):
            median = (-lower_half[0] + upper_half[0]) / 2.0
        else:
            median = -lower_half[0] / 1.0  
    
    
        result.append(format(median, ".1f"))
    
    return result
    

    if name == "main": input = sys.stdin.read().strip().split() n = int(input[0]) a = list(map(int, input[1:n+1])) medians = runningMedian(a) for median in medians: print(median)