import heapq
class StreamStatistics:
def __init__(self):
self._low = [] # max-heap (нижняя половина), хранится как min-heap с отрицанными значениями
self._high = [] # min-heap (верхняя половина)
def addValue(self, number: float) -> None:
if not self._low or number <= -self._low[0]:
heapq.heappush(self._low, -number)
else:
heapq.heappush(self._high, number)
# Балансировка размеров куч (разница не больше 1)
if len(self._low) > len(self._high) + 1:
heapq.heappush(self._high, -heapq.heappop(self._low))
elif len(self._high) > len(self._low) + 1:
heapq.heappush(self._low, -heapq.heappop(self._high))
def getMedian(self) -> float:
if not self._low and not self._high:
raise ValueError("Поток пуст, медиана не определена")
if len(self._low) == len(self._high):
return (-self._low[0] + self._high[0]) / 2.0
if len(self._low) > len(self._high):
return float(-self._low[0])
return float(self._high[0])