Welford Online Mean and Variance
~20 mincode completion
Implement welford_mean_var(values) that returns (mean, variance) as a tuple of two floats.
Examples
Classic Welford example: mean=5.0, variance=4.0
- Input
- welford_mean_var([2, 4, 4, 4, 5, 5, 7, 9])
- Output
- [5, 4]
All identical values: variance is 0
- Input
- welford_mean_var([3, 3, 3, 3])
- Output
- [3, 0]
Two values: mean=3.0, variance=1.0 (population)
- Input
- welford_mean_var([2, 4])
- Output
- [3, 1]
Hints
Hint 1
Walk the input once and accumulate as you go.
Hint 2
Watch for this: computed sample variance dividing by n minus 1.
Requirements
: Iterable of numeric values (list or 1D array)
Return Tuple (mean, variance) as Python floats.
Constraints
Standard library only, no imports required
Time limit: 200 ms, Memory: 64 MB
Where this shows up
~20 min
••••••••••••••••
8 employers weight this skill
4 big tech firms, 1 AI product company, 1 enterprise vendor, 1 defense company, 1 quant fund. Top match scores 93.
Python
def welford_mean_var(values) -> tuple:
"""
Compute mean and population variance using Welford's single-pass algorithm.
Args:
values: Iterable of numeric values (list or 1D array)
Returns:
Tuple (mean, variance) as Python floats.
"""
# YOUR CODE HERE
pass