Moving Average
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?
- Raises an error
- Drops the oldest item automatically
- 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.)
VISIBLE = 3
CASES = [
('result = list(moving_average([1, 2, 3, 4], 2))', [1.0, 1.5, 2.5, 3.5], 'a window of two'),
('result = list(moving_average([10, 20, 30], 3))', [10.0, 15.0, 20.0], 'a window as large as the list'),
('result = list(moving_average([], 3))', [], 'no values'),
('result = list(moving_average([5, 7], 1))', [5.0, 7.0], 'a window of one'),
('result = list(moving_average(iter([2, 4, 6, 8]), 2))', [2.0, 3.0, 5.0, 7.0], 'an iterator'),
('result = error_of(lambda: next(moving_average([1], 0)))', 'ValueError', 'a window of zero'),
('consumed = []\ndef source():\n for i in range(10):\n consumed.append(i)\n yield i\ng = moving_average(source(), 3)\nnext(g)\nnext(g)\nresult = len(consumed)', 2, 'it is lazy'),
('result = list(moving_average([1, 2, 3, 4, 5], 10))', [1.0, 1.5, 2.0, 2.5, 3.0], 'a window larger than the data'),
]