Moving average with deque

MediumCollections Programs · 11 of 20

Write a Python program to compute a moving average over a window of 3 values.

Advertisement
Output
[20.0, 30.0, 40.0]

Approach

  1. Keep the window in a deque with maxlen and average it each step.

Solution

Python
from collections import deque values = [10, 20, 30, 40, 50]window = deque(maxlen=3)averages = []for v in values:    window.append(v)    if len(window) == 3:        averages.append(sum(window) / 3)print(averages)
Output
[20.0, 30.0, 40.0]

Learn the concept

New to this topic? Read the lesson, then come back.

More collections programs

← All 20 Collections Programs

Leave a Comment