🧭 Do not search for the first 15 minutes. When stuck: re-read the requirements → define I/O → choose the data structure → trace a small example by hand → write code.
You are given an account system's transaction log in chronological order. Each line is one deposit or withdrawal, and the same user appears many times.
Implement calculate_balances(transactions), which sums every transaction per
user to produce a final balance.
transactions = [("alice", 100), ("bob", -30), ("alice", 50), ("bob", 20)]
(user, amount) pair.Return a list of (user, balance) tuples sorted by user name in ascending order.
calculate_balances(transactions)
# [("alice", 150), ("bob", -10)]
Where each value comes from:
The result is ordered by sorted name, not by order of appearance. alice happens to
come first in the input, but even if bob had come first the result would still be
[("alice", 150), ("bob", -10)].
Use Python's default string comparison — the same result as calling sorted
without a key.
That comparison follows character codes, so uppercase sorts before lowercase.
Sorting "Banana" and "apple" puts "Banana" first. It reads oddly as
dictionary order, but here that behavior is the correct answer.
("a", 0).Implement calculate_balances(transactions).