Problem 268456 · easy · Level 02 Linear Data Structures

Whole Batch or Sample?

variance · standard deviation · population vs sample · loops

A bakery weighs its loaves (in grams). Sometimes the list holds every loaf of a batch, and sometimes only a sample of loaves picked from a much larger day's production, used to estimate the spread of all of them.

Write spread(weights, kind) that returns the tuple (variance, sd):

  • kind == "population": the list is the whole batch; divide the sum of squared deviations from the mean by n.
  • kind == "sample": the list is a sample; divide by n - 1. A sample of a single loaf says nothing about spread, so return None in that case.

sd is the square root of variance. Return plain floats.

Examples

Input:  weights = [4, 8, 6, 5, 7], kind = "population"
Output: (2.0, 1.4142135623730951)
Explanation: the mean is 6; the squared deviations 4, 4, 0, 1, 1 add up to 10, and 10 / 5 = 2.

Input:  weights = [4, 8, 6, 5, 7], kind = "sample"
Output: (2.5, 1.5811388300841898)
Explanation: the same sum 10, divided by 5 - 1 = 4.

Input:  weights = [812], kind = "sample"
Output: None

Constraints

  • 1 <= len(weights) <= 10**5
  • every weight is a number with 0 <= weight <= 5000
  • kind is "population" or "sample"
  • floats are compared with a tolerance of 1e-6

Goals

  • Compute the variance as the average squared deviation from the mean
  • Choose the divisor n for a whole population and n - 1 for a sample
  • Take the square root to get back to the data's units
Starting Python…