Compute variance of a list in Python
PayPalData Scientist · Technical ScreenLast updated
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 (n\ge 1)) - Clarify whether you are computing:
- Population variance: (\sigma^2 = \frac{1}{n}\sum_{i=1}^n (x_i-\bar{x})^2), or
- Sample variance: (s^2 = \frac{1}{n-1}\sum_{i=1}^n (x_i-\bar{x})^2) (requires (n\ge 2))
- 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).
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.