Seasonal Averages: One per Position in the Cycle

Time SeriesMedium+15 XP+15

Seasonal Averages: One per Position in the Cycle

Many series repeat on a fixed cycle: traffic by hour of day, sales by day of week, demand by month. To see that pattern you average every value that shares the same position in the cycle — all the Mondays together, all the Tuesdays together, and so on.

Task: write seasonal_average(series, period) returning period averages, each rounded to 4 decimal places.

  • Position p of the output averages series[p], series[p + period], series[p + 2·period], …
  • The output always has exactly period entries, whatever the length of the series.
  • The series need not be a whole number of cycles long. When it isn't, the early positions have one more value to average than the later ones — average whatever each position actually has, rather than discarding the partial cycle.
  • Every position has at least one value.

Python's extended slice does the grouping in one expression: series[p::period] takes every period-th element starting at p.

What you get back is the seasonal profile, and it's useful in two directions. Read forwards, it's the shape of the cycle — Saturdays are busy, Tuesdays are dead. Read backwards, it's something to subtract: take each value minus its position's average and the cycle disappears, leaving the trend and the genuinely unusual days visible. That subtraction is seasonal adjustment, and it's why this simple average is the first step of nearly every seasonal decomposition.

Examples

series = [10, 20, 12, 22]
period = 2
returns [11.0, 21.0]
series = [1, 10, 2, 20, 3]
period = 2
returns [2.0, 15.0]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run