Moving Median: Smoothing That Ignores Glitches

Time SeriesEasy+10 XP+10

Moving Median: Smoothing That Ignores Glitches

A moving average is the usual way to smooth a noisy series, and it has one weakness: a single absurd reading — a sensor glitch, a fat-fingered entry — drags every window it touches. A moving median ignores it entirely, because the median only cares about the middle position, not the magnitudes.

Task: write moving_median(series, window) returning the median of each window, each rounded to 4 decimal places.

  • Slide a window of window consecutive values along the series. The output has len(series) - window + 1 entries.
  • For each window: sort it, then take the middle value if window is odd, or the average of the two middle values if it's even.
  • Sort the window's own values; don't assume the series arrives sorted.
  • A window of 1 returns the series itself.

The contrast is worth running yourself. On [10, 1, 1, 1, 100] with a window of 5, the mean is 22.6 — a number no reading in the series is anywhere near — while the median is 1, which is what the series is plainly doing. The two outliers cannot move it, because moving the median would require changing which value is in the middle, and a single extreme reading only occupies one slot however extreme it gets.

The cost is speed. A moving average can slide in constant time per step by adding the entering value and subtracting the leaving one; a median has no such shortcut and needs the window re-sorted (or a cleverer structure) each time.

Median Explorer

Visualize how sorting reveals the exact center of a dataset.

Outlier Resistance
Dataset size: 0 (Even)
Median (Middle Value)Stable
0

The center value in the ordered list is 5.

Mean (Arithmetic Average)Sensitive
0.0

The sum of all values divided by 5 is 5.2.

Examples

series = [1, 5, 2, 8, 3]
window = 3
returns [2.0, 5.0, 3.0]
series = [1, 2, 3, 4]
window = 2
returns [1.5, 2.5, 3.5]

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