Drill

ProblemsPython › reporting

Average spend per category

mediumreportingPython

A budgeting view shows what a typical transaction looks like in each category.

average_per_category(entries: list<Entry>) → map<string, int>

Solve it in the editor →

Where you start

def average_per_category(entries: list[Entry]) -> dict[str, int]:
    

Worked examples

CallResult
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()}

The same problem in another language

More reporting problems in Python