Linear Interpolation: Bridging Gaps in a Series

Time SeriesMedium+15 XP+15

Linear Interpolation: Bridging Gaps in a Series

A sensor drops out for a few readings. Filling those gaps with the column mean would be absurd for a time series — the value at 3pm is far better guessed from 2pm and 4pm than from the whole day's average. Linear interpolation draws a straight line between the two known readings on either side of a gap and reads the missing values off it.

Task: write interpolate_missing(series) returning a new list with the interior gaps filled, each filled value rounded to 4 decimal places.

  • A gap is None. Everything else is a number.
  • For a gap between a known value at index left and the next known value at index right, each missing position left + k becomes:
series[left]+k⋅series[right]−series[left]right−leftseries[left] + k \cdot \frac{series[right] - series[left]}{right - left}series[left]+k⋅right−leftseries[right]−series[left]​
  • Leading and trailing gaps stay None. With known values on only one side there is no line to draw, and extending the last slope outward is extrapolation — a guess of a completely different character, and not what's being asked for here.
  • Values that were already present are returned unchanged, not re-rounded.
  • A series with no gaps comes back as it went in.

The quiet reason this matters more than it looks: imputing with a global statistic flattens exactly the local structure a time-series model is trying to learn. Interpolation preserves the shape of the trend through the gap, so the smoothed series still has the slope it should.

Examples

series = [1, None, 3]
returns [1, 2.0, 3]
series = [None, 2, None, None, 8, None]
returns [None, 2, 4.0, 6.0, 8, None]

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