53Statistics across many nodes
53 Statistics across many nodes
Anthropic coding rounds asked for the mode and the median of data that sits on many nodes, through a supplied messaging interface (2 sources). This is practice in that shape, not a leaked question. Use only the standard library.
Set a 40-minute timer. Read one level at a time, and run only that level's tests until they pass:
pytest problems/53_distributed_stats -k level1. Earlier levels must keep passing.
Level 1. Mean and variance. summarize(values) returns one node's summary as (count, mean, m2), where m2 is the
sum of squared distances from the node's own mean. An empty node gives (0, 0.0, 0.0), and merging two empty summaries gives (0, 0.0, 0.0) too. merge(a, b) returns the
summary of two nodes' values together, from the two summaries alone: with δ the second mean minus the first and n the
total count, the mean moves by δ times the second node's share of n, and m2 is the two m2s plus δ² × na × nb / n.
mean_and_variance(summaries) merges every node's summary and returns the overall mean and the sample variance,
m2 / (n − 1).
Level 2. Mode. global_mode(nodes) takes each node's list of integers and returns the most common value
overall, and the smallest such value on a tie.
Level 3. Median. distributed_median(nodes) returns the lower median of all the integers: the value at position
(N − 1) // 2 when all N values are sorted. Each node answers only size(), lowest(), highest() and
count_leq(v), the number of its values at or below v. A node can be empty, and an empty node's lowest() and
highest() raise IndexError, so check size() first. Values can be negative. The tests count the count_leq calls, so ask for counts at
values you choose instead of scanning: about 12 rounds of 10 calls is the budget for values up to 4,095.
Things to get right: the cross term when you merge variances, weighting the means by counts, subtracting the mean before squaring, local modes that aren't the global one, the lower middle on an even count, and the message budget. Follow-ups from the lesson: sending each value to one owner node, heavy hitters, and approximate quantile sketches.