Quick Overview

This question evaluates understanding of statistical measures and numeric computation, focusing on implementing variance calculations (population vs sample) and considerations for numerical stability.

Compute variance of a list in Python

Company: PayPal

Role: Data Scientist

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Technical Screen

## 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`/`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).

Quick Answer: This question evaluates understanding of statistical measures and numeric computation, focusing on implementing variance calculations (population vs sample) and considerations for numerical stability.

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.

Examples

Input: ([2, 4, 6, 8],)

Expected Output: 5.0

Explanation: mean=5; squared deviations 9,1,1,9 sum to 20; 20/4 = 5.0.

Input: ([1, 1, 1, 1],)

Expected Output: 0.0

Explanation: All elements equal the mean, so every deviation is 0.

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.

Loading coding console...