The Shifting Standard

A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
medium
Seniority
L5
Asked in
Meta

Problem

Our live sensor dashboard drifts away from the true average whenever a small batch of readings lands between large ones. After each of the batches, in arrival order, report the average of every individual reading received so far; a later batch can arrive empty, but the first never does.

A benchmark in motion.

Example 1

Input:

batches = [[10,20],[30],[40,50,60]]

Output:

[15,20,35]

Example 2

Input:

batches = [[100]]

Output:

[100]

Worked solution and explanation

What this really is

This is a weighted mean dressed up as a dashboard bug. The skill is carrying one pooled pair of state, total_sum and total_count, across groups of unequal size. Almost everyone keeps some state; the trap is keeping the wrong state, either the current batch's average or a list of per-batch averages. On the example that gives 30.0 or 22.5 where the answer is 20.0, because a one-reading batch gets the same vote as a two-reading one.

Mean of batch means
After [10, 20] and [30], averaging 15.0 and 30.0 gives 22.5. The lone reading of 30 carries as much weight as the two readings before it.
Pooled readings
A sum of 60 over 3 readings gives 20.0. Every reading counts once, whichever batch carried it.

Step 1: Carry the sum and the count, not an average

An average cannot be updated on its own: to fold in a new batch you need to know how many readings stand behind it. Keep total_sum and total_count, and derive the average only at the moment you report.

Step 2: Report once per batch, after the batch is folded in

The output is positional: one value per batch, in arrival order. So the append sits in the outer loop, after the inner loop has added every reading of that batch. An empty batch adds nothing, and the same average is reported again.

Pooled sum and count across batches
def the_shifting_standard(batches: list[list[float]]) -> list[float]:
    total_sum = 0
    total_count = 0
    averages = []
    for batch in batches:
        for value in batch:
            total_sum += value
            total_count += 1
        average = total_sum / total_count
        averages.append(average)
    return averages

Common follow-up questions