Coding questions · PayPal
Compute variance of a list in Python
This question evaluates understanding of statistical measures and numeric computation, focusing on implementing variance calculations (population vs sample) and considerations for numerical stability.
Task
Given a Python list of numbers (ints/floats), write code to compute its variance.
Requirements
- Input:
nums: list[float](length ) - Clarify whether you are computing:
- Population variance: , or
- Sample variance: (requires )
- Avoid using
numpy/pandasunless explicitly allowed. - State time and space complexity.
Follow-ups (optional)
- Implement a numerically stable one-pass version.
- Handle edge cases (empty list, single element, very large numbers).
Compute Variance of a List
Given a list of numbers nums (length n >= 1), compute and return its population variance as a float:
variance = (1/n) * sum((x_i - mean)^2) for i = 1..n, where mean = (1/n) * sum(x_i)
Do not use numpy or pandas. For a single-element list the variance is 0. Return the result as a floating-point number.
Examples:
nums = [2, 4, 6, 8]-> mean = 5, variance = (9+1+1+9)/4 =5.0nums = [1, 1, 1, 1]->0.0nums = [10, 20]-> mean = 15, variance = (25+25)/2 =25.0
Constraints
- 1 <= n <= 10^6
- Each element is an int or float.
- Use population variance (divide by n), not sample variance.
- Do not use numpy or pandas.
Hints
- First compute the mean = sum(nums) / n.
- Then sum the squared differences (x - mean)^2 over all elements.
- Divide that sum by n (population variance). For n == 1 the result is 0.