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.
window consecutive values along the series. The output has len(series) - window + 1 entries.window is odd, or the average of the two middle values if it's even.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.