──────────────────────────────────────

66. Weekly Activity Digest Capstone · Build the Core Calculation

Summarise two valid groups and test the calculation apart from display.

Lesson files · lessons/automation-capstone/build-the-digest-core

Before you start
- Group repeated records in a dictionary.
- Return a calculation from a function and display the result in its caller.

By the end
- Use a reusable function to total minutes for repeated groups.
- Print the group totals alphabetically and explain how a second caller could use the returned totals.

Where you can use it
Reuse the same group totals in a console report and in a different export without recalculating them.

The calculation needs records and should return a result. A different caller can then print a report, export a spreadsheet-friendly table or test a calculation. Use a dictionary because a group name identifies each running total.

Predict
Where should summary headings be printed?
- Inside every loop iteration.
- Outside the calculation function.

Worked example (example.py)

def summarise(rows):
    totals = {}
    for group, minutes in rows:
        totals[group] = totals.get(group, 0) + minutes
    return totals

print(summarise([("Garden", 10), ("Garden", 0)]))


Example result
{'Garden': 10}

Predict the minutes for each group in [("Robots", 20), ("Garden", 10), ("Robots", 15)]. Pass the rows to summarise and compare the returned totals with your prediction. Then print the groups alphabetically, with each group name followed by a colon, a space and its minutes.

Starter program (starter.py)

def summarise(rows):
    totals = {}
    for group, minutes in rows:
        totals[group] = totals.get(group, 0) + minutes
    return totals

print(summarise([("Garden", 10), ("Garden", 0)]))


Hint
Keep the function. Sort its keys and format each result after it returns.

Case 1. Try the sample
Input
(No input.)
Expected output
Garden: 10
Robots: 35

Stretch
Add a test for summarise([]) and one for a real zero-minute session.

Reflect
Which caller could use the returned dictionary in a different way?

Check your prediction
Outside the calculation function. Building the result without output lets other callers use it.
