Real metrics pipelines are streaming: values arrive one at a time and you report the average over the last size readings. This is a fixed window over an unbounded stream. Keep a deque of the current values and a running total. On each new value, append it and add it to the total; if the deque now exceeds size, pop the oldest from the left and subtract it. Return total divided by the current count.
Implement the MovingAverage class with init(self, size) and next(self, value) returning the average of the last size values (float division).
Example: with MovingAverage(3), calling next(1), next(10), next(3) returns 1.0, 5.5, then (1 + 10 + 3) / 3.
from collections import deque
def max_sum_window(nums, k):
if k <= 0 or k > len(nums):
return None
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k]
if window > best:
best = window
return best
def longest_unique(s):
last = {}
start = 0
best = 0
for i, ch in enumerate(s):
if ch in last and last[ch] >= start:
start = last[ch] + 1
last[ch] = i
length = i - start + 1
if length > best:
best = length
return best
def longest_at_most_k_distinct(s, k):
if k <= 0:
return 0
counts = {}
start = 0
best = 0
for i, ch in enumerate(s):
counts[ch] = counts.get(ch, 0) + 1
while len(counts) > k:
left = s[start]
counts[left] -= 1
if counts[left] == 0:
del counts[left]
start += 1
length = i - start + 1
if length > best:
best = length
return best
def max_window(nums, k):
if k <= 0 or k > len(nums):
return []
dq = deque()
result = []
for i, val in enumerate(nums):
while dq and nums[dq[-1]] <= val:
dq.pop()
dq.append(i)
if dq[0] <= i - k:
dq.popleft()
if i >= k - 1:
result.append(nums[dq[0]])
return result
class MovingAverage:
# TODO: implement a streaming moving average over the last size values.
# __init__ stores size and sets up a deque plus a running total.
# next(value) appends value, drops the oldest if over size, and returns
# the average of the current window as a float.
def __init__(self, size):
pass
def next(self, value):
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Real metrics pipelines are streaming: values arrive one at a time and you report the average over the last size readings. This is a fixed window over an unbounded stream. Keep a deque of the current values and a running total. On each new value, append it and add it to the total; if the deque now exceeds size, pop the oldest from the left and subtract it. Return total divided by the current count.
Implement the MovingAverage class with init(self, size) and next(self, value) returning the average of the last size values (float division).
Example: with MovingAverage(3), calling next(1), next(10), next(3) returns 1.0, 5.5, then (1 + 10 + 3) / 3.
Press Run Tests or ββ© to check your solution.