Medium: Interview Core · Problem 57 of 82

Moving Average

MediumStandard LibraryPython

Write a generator moving_average(values, window). For each value it reads, it yields the average of the last window values seen so far (fewer at the start, when fewer values exist). It must work on any iterable and be lazy. If window is less than 1, raise ValueError when the first value is requested.

For [1, 2, 3, 4] with window=2 it yields 1.0, 1.5, 2.5, 3.5.

Understand the problem

Do the first few averages by hand.

For [1, 2, 3, 4] with window=2, what is the third output? (The average of the last two values at that point.)

After reading 1, 2, 3 the last two values are 2 and 3: their average is 2.5. The first output is the average of just [1], because there is only one value yet.

What does deque(maxlen=3) do when you append a fourth item?

  1. Raises an error
  2. Drops the oldest item automatically
  3. Ignores the new item

A deque with maxlen is a fixed-size window: adding to one end pushes the item at the other end out, in O(1). That is exactly a sliding window.

Write the solution

A generator function.

def moving_average(values, window):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

What structure keeps only the most recent window values and forgets the older ones by itself?

Hint 2: the shape of the answer

recent = deque(maxlen=window). For each value: recent.append(value), then yield sum(recent) / len(recent). Check window first.

Reflect

Solution

from collections import deque

def moving_average(values, window):
    if window < 1:
        raise ValueError("window must be at least 1")
    recent = deque(maxlen=window)
    for value in values:
        recent.append(value)
        yield sum(recent) / len(recent)

Another way: keep a running total

from collections import deque

def moving_average(values, window):
    if window < 1:
        raise ValueError("window must be at least 1")
    recent = deque()
    total = 0
    for value in values:
        recent.append(value)
        total += value
        if len(recent) > window:
            total -= recent.popleft()
        yield total / len(recent)

What this tests: collections.deque with maxlen, generators, and the sliding-window idea.

The efficient version: sum(recent) adds up window numbers each time, O(window) per value. Keeping a running total (add the new value, subtract the one that leaves) makes each step O(1). For small windows sum is fine; for large ones the running total wins. (With floats, a running total can drift slightly.)

Why a deque and not a list? list.pop(0) shifts every item (O(n)). deque.popleft() is O(1). Use a deque whenever you add at one end and remove at the other.

Streams: the generator holds only window values, so it can process an endless stream.

What an interviewer might ask next: Yield only once the window is full. (Skip the output while len(recent) < window.)