Neural Mastery
← Practice
Streaming Moving Variance (Welford)easy

Streaming Moving Variance (Welford)

easy NumPy & Data Wrangling 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Linear algebra step 1/4

A vector transforms

Matrix multiplication is the first computation behind every model.
Open lesson →
01vector
02matrix
03transform
04result
[2, −1] × [[1, 2], [−.5, 1]] = [0, −2]

Computed matrix × vector transformation

Compute running sample mean and sample variance in a single pass using Welfords algorithm.

Task

Implement streaming_moving_variance(stream): for each incoming float, maintain running count n, mean, and sum of squared differences M2 via Welfords algorithm. Sample variance is M2 / (n - 1) for n >= 2 (and 0.0 for n <= 1). Return list of dicts with "count", "mean", and "variance", rounded to 4 decimal places.

Function Signature

streaming_moving_variance(stream: list[float]) -> list[dict]

Examples

Example 1: Three integers stream
Input: stream = [2, 4, 4]
Output: [{'count': 1, 'mean': 2, 'variance': 0}, {'count': 2, 'mean': 3, 'variance': 2}, {'count': 3, 'mean': 3.3333, 'variance': 1.3333}]
Example 2: Constant stream variance zero
Input: stream = [5, 5, 5]
Output: [{'count': 1, 'mean': 5, 'variance': 0}, {'count': 2, 'mean': 5, 'variance': 0}, {'count': 3, 'mean': 5, 'variance': 0}]

Constraints

  • stream is a list of floats
Python3Saved ✓
def streaming_moving_variance(stream: list[float]) -> list[dict]:
"""Compute running count, mean, and sample variance using Welford's algorithm.
Returns list of dicts with keys 'count', 'mean', 'variance'.
"""
pass

Case 1: Three integers stream
Input: stream = [2, 4, 4]
Expected: [{'count': 1, 'mean': 2, 'variance': 0}, {'count': 2, 'mean': 3, 'variance': 2}, {'count': 3, 'mean': 3.3333, 'variance': 1.3333}]
Case 2: Constant stream variance zero
Input: stream = [5, 5, 5]
Expected: [{'count': 1, 'mean': 5, 'variance': 0}, {'count': 2, 'mean': 5, 'variance': 0}, {'count': 3, 'mean': 5, 'variance': 0}]