Totals per category
A ledger groups every sale under its category so each bucket shows a single sum.
- Add the amounts of every sale under the same category.
- Every category that appears earns an entry in the result.
- The result is one running total per category.
sum_per_category(sales: list<Sale>) → map<string, int>
Where you start
def sum_per_category(sales: list[Sale]) -> dict[str, int]:
Worked examples
| Call | Result |
|---|---|
sum_per_category([Sale(category="food", amount=10), Sale(category="food", amount=15)]) | {"food": 25} |
sum_per_category([Sale(category="a", amount=3), Sale(category="b", amount=4), Sale(category="a", amount=5)]) | {"a": 8, "b": 4} |
sum_per_category([Sale(category="x", amount=1)]) | {"x": 1} |
sum_per_category([Sale(category="p", amount=0), Sale(category="q", amount=-2)]) | {"p": 0, "q": -2} |
Hint
Aggregate into a map keyed by category, adding each amount as you go.
Reference solution in Python
def sum_per_category(sales: list[Sale]) -> dict[str, int]:
result = {}
for s in sales:
result[s.category] = result.get(s.category, 0) + s.amount
return result