Average spend per category
A budgeting view shows what a typical transaction looks like in each category.
- Amounts are never negative.
- The average is a whole number, rounded half up: 12.5 becomes 13.
- A category with no entries never appears.
average_per_category(entries: list<Entry>) → map<string, int>
Where you start
def average_per_category(entries: list[Entry]) -> dict[str, int]:
Worked examples
| Call | Result |
|---|---|
average_per_category([Entry(category="food", amount=10), Entry(category="food", amount=15)]) | {"food": 13} |
average_per_category([Entry(category="rent", amount=3000), Entry(category="food", amount=40), Entry(category="food", amount=20)]) | {"rent": 3000, "food": 30} |
average_per_category([Entry(category="x", amount=0)]) | {"x": 0} |
average_per_category([]) | {} |
Hint
Collect sums and counts side by side, then divide once at the end. (sum + count / 2) / count rounds half up in integers.
Reference solution in Python
def average_per_category(entries: list[Entry]) -> dict[str, int]:
sums = {}
counts = {}
for e in entries:
sums[e.category] = sums.get(e.category, 0) + e.amount
counts[e.category] = counts.get(e.category, 0) + 1
return {k: (s + counts[k] // 2) // counts[k] for k, s in sums.items()}