The Minutes Tracker

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
L3
Asked in
W. W. Grainger

Problem

Our weekly fitness report shows blank totals for some users and too-small totals for others who logged several workouts. Given a user record, return the total minutes across everything in its activities, where a user who logged nothing totals 0.

Some activities eat more time than others.

Example

Input:

user = {"name":"Alice","email":"a@x.com","activities":[{"type":"run","minutes":30},{"type":"swim","minutes":45}]}

Output:

75

Worked solution and explanation

The bug that looks like a lookup

This is a sum over a variable-length list dressed up as a user profile. Anyone can reach into user['activities']. What separates candidates is whether they treat that list as having a length they do not know. Reach for user['activities'][0]['minutes'] and the code looks right on a single-workout user. Then it raises IndexError on a user with no activities and quietly reports 120 for someone who actually logged 225.

Step 1: Start the total at zero

Seed total = 0 before touching the list. That one line is the whole empty-case answer: a user who logged nothing never enters the loop, and 0 comes back without a special branch.

Step 2: Add every activity, not one

Walk all of user['activities'] and add each activity['minutes'] to total. The list can hold zero, one or many entries, so no fixed index can stand in for the walk.

Accumulate across the whole list
def total_activity_minutes(user):
    total = 0
    for activity in user["activities"]:
        total += activity["minutes"]
    return total
Fixed index
user['activities'][0]['minutes'] returns 30 for Alice instead of 75, and crashes on an empty list.
Whole list
The loop over user['activities'] returns 75 for Alice, 225 for Dan and 0 for Bob, with no branching.

Common follow-up questions