Daily active users are noisy, so the product team reports a smoothed trend line instead.
Write a function moving_average(values, window) that returns a list of rolling averages, each rounded to 2 decimals. Use only full windows — a list of length n with window k returns n - k + 1 values. Return an empty list if the window is larger than the data.
This fixture runs before your code on every Run and Submit, so the data is always clean.
import numpy as np
dau = [120, 132, 101, 134, 190, 230, 210, 205, 240, 250]- Step 1: Convert to a float array and validate the window — a window of 0 or one longer than the data has no valid position.
- Step 2: `np.ones(window) / window` builds an averaging kernel: `window` weights that each equal `1/window`.
- Step 3: `np.convolve(arr, kernel, mode="valid")` slides that kernel across the array and keeps only positions where it fully overlaps — exactly the `n - k + 1` full windows requested.
- Step 4: Round to 2 decimals and call `.tolist()` to hand back plain Python floats.
- Step 5: In a pandas pipeline the equivalent is `series.rolling(window).mean().dropna()` — worth mentioning in an interview.
import numpy as np
def moving_average(values, window):
arr = np.asarray(values, dtype=float)
if window <= 0 or window > arr.size:
return []
kernel = np.ones(window) / window
return np.round(np.convolve(arr, kernel, mode="valid"), 2).tolist()Learn the concept first
Stuck on NumPy? These free Python lessons teach it step by step.
More NumPy questions
Asked at Google
Practising alone only goes so far — our live cohorts pair Python and Pandas depth with dashboards, agentic analytics projects and mock interviews.
Explore the program