A Scale That Can't Remember

Descriptive StatisticsMedium+20 XP+20

A Scale That Can't Remember

A precision scale on a packing line weighs one bag at a time and reports in micrograms, so a 1 kg bag reads about 1 000 000 0001\,000\,000\,0001000000000. Its tiny controller cannot store past readings: between bags it may keep only a few running numbers.

After every bag, the display must show two statistics for all bags weighed so far:

  • the mean, and
  • the population variance: the average squared deviation from the mean, dividing by the number of readings NNN, as in the chapter.

Task: write running_stats(readings) that walks through readings in order and returns a list with one (mean, variance) tuple per reading (the statistics of every reading up to and including that one), with both numbers rounded to 4 decimal places.

Your method has to stay accurate when the readings are huge but close together, like bags that all weigh about a kilogram and differ by only a few micrograms.

Examples

readings = [2, 4, 6, 8, 10]
returns [(2.0, 0.0), (3.0, 1.0), (4.0, 2.6667), (5.0, 5.0), (6.0, 8.0)]
readings = [1000000004, 1000000007, 1000000013, 1000000016, 1000000010]
returns [(1000000004.0, 0.0), (1000000005.5, 2.25), (1000000008.0, 14.0), (1000000010.0, 22.5), (1000000010.0, 18.0)]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run