Neural Mastery
← Practice
Practice: Sample Mean and Variance From Scratcheasy

Practice: Sample Mean and Variance From Scratch

easy Math for ML 10–15 min

NumPy allowed · plain Python earns 10 bonus points

New to this topic? Mathematics for AI Overview
Study this concept first →
Linear algebra step 1/4

A vector transforms

Matrix multiplication is the first computation behind every model.
Open lesson →
01vector
02matrix
03transform
04result
[2, −1] × [[1, 2], [−.5, 1]] = [0, −2]

Computed matrix × vector transformation

Compute the sample mean and population variance of a numerical series from scratch.

Task

Implement sample_mean_and_variance(data). Return [mean, variance] where mean = sum(data)/n and variance = sum((x - mean)**2)/n. Raise ValueError if data is empty.

Function Signature

sample_mean_and_variance(data: list[float]) -> tuple[float, float]

Examples

Example 1: Simple integer sequence
Input: data = [1, 2, 3, 4, 5]
Output: [3, 2]
Example 2: Constant data with zero variance
Input: data = [4, 4, 4]
Output: [4, 0]

Constraints

  • data is a non-empty list of numbers
  • Raise ValueError on empty input
  • Return list or tuple of two floats [mean, variance] rounded to 6 decimal places
Python3Saved ✓
def sample_mean_and_variance(data: list[float]) -> tuple[float, float]:
"""Compute (mean, variance) of a list of numbers.
Raise ValueError if data is empty.
"""
# Your code here
pass

Case 1: Simple integer sequence
Input: data = [1, 2, 3, 4, 5]
Expected: [3, 2]
Case 2: Constant data with zero variance
Input: data = [4, 4, 4]
Expected: [4, 0]