cswork / libraryOpen practice workspace

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 n≥1n\ge 1)
  • Clarify whether you are computing:
    • Population variance: σ2=1n∑i=1n(xi−xˉ)2\sigma^2 = \frac{1}{n}\sum_{i=1}^n (x_i-\bar{x})^2, or
    • Sample variance: s2=1n−1∑i=1n(xi−xˉ)2s^2 = \frac{1}{n-1}\sum_{i=1}^n (x_i-\bar{x})^2 (requires n≥2n\ge 2)
  • Avoid using numpy/pandas unless 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.0
  • nums = [1, 1, 1, 1] -> 0.0
  • nums = [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

  1. First compute the mean = sum(nums) / n.
  2. Then sum the squared differences (x - mean)^2 over all elements.
  3. Divide that sum by n (population variance). For n == 1 the result is 0.