Moving average in Python
Smoothing a stream of numbers with a sliding window.
from collections import deque
def moving_average(values, window):
buf = deque(maxlen=window)
for value in values:
buf.append(value)
yield sum(buf) / len(buf)
How it works
- A
dequewithmaxlenholds the sliding window. - Each new value pushes the oldest one out.
- Yields the running mean after every step.
Keywords and builtins used here
defforlenmoving_averagesumyield
The run, in numbers
- Lines
- 7
- Characters to type
- 158
- Tokens
- 41
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 25 seconds.
Step 3 of 7 in Iterators, errors & files, step 46 of 72 in Language basics.