Group Average
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L4
Problem
Metric readings arrive in data as [name, value] pairs, and the same name can repeat any number of times within a batch. The result maps each name to the average of every value recorded under it.
Same group, different values. What is typical?
Example 1
Input:
data = [["a",10],["b",20],["a",30]]
Output:
{"a":20,"b":20}Example 2
Input:
data = [["x",100]]
Output:
{"x":100}Worked solution and explanation
What this really is
This is a grouped mean dressed up as a dictionary exercise, and the only thing it grades is whether your divisor belongs to the key. Anyone can build a dict from pairs. The trap is treating each pair as the value for its name: dict(data) or result[key] = value keeps the last write, so the first example returns 30 for 'a' instead of 20.0. Worse, that version passes every input where each name appears once, so the bug ships quietly.
Step 1: Keep two numbers per key
A mean needs a total and a count, and both have to be scoped to the same key. One accumulator is not enough. Dividing by len(data) mixes every name's readings into a single divisor, and storing only the latest value throws the earlier readings away.
Step 2: Divide once, after the last pair
A key's count is final only when the input is exhausted. Walk the keys in sums and divide by counts[key]. An empty input never creates a key, so the result is an empty dict with no special case.
def group_averages(data):
sums = {}
counts = {}
for pair in data:
key = pair[0]
value = pair[1]
if key not in sums:
sums[key] = 0
counts[key] = 0
sums[key] += value
counts[key] += 1
result = {}
for key in sums:
result[key] = sums[key] / counts[key]
return result- Last write wins
result[key] = valuefor each pair. For the first example, 'a' ends at 30, and a test with only single readings never notices.- Sum and count per key
sums[key] += valueandcounts[key] += 1, thensums[key] / counts[key]. 'a' gets (10 + 30) / 2 = 20.0.
Common follow-up questions
- What if you also needed the min and max reading per name? (Extending the per-key accumulator beyond sum and count.)
- Readings arrive one at a time and the dashboard needs each name's current average after every reading. What changes? (Online averaging with state kept per key.)
- What if some readings carry `None` because the sensor dropped out? (Whether a missing reading counts toward the divisor.)