We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Find the Running Median
You are viewing a single comment's thread. Return to all comments →
Python3
import heapq import sys
def runningMedian(a):
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)