Model df.resample("ME", on="date")["amount"].sum(), which includes the empty months between the first and the last.
What to build
A program that totals amounts per calendar month, including empty months.
Requirements
- Print
YYYY-MM TOTALfor every month from the earliest to the latest record, in order, with the total to two decimals; months without records show 0.00. - Then print
best YYYY-MM, the month with the largest total, the earliest one on a tie.
Input
Line 1: n. Then n lines YYYY-MM-DD AMOUNT, in any order.
Output
One line per month, then one line.
Constraints
1 ≤ n ≤ 1000; dates span at most 10 years; amounts are 0 or more.
Example
Input:
3
2024-01-05 10
2024-01-20 5
2024-03-02 7
Output:
2024-01 15.00
2024-02 0.00
2024-03 7.00
best 2024-01
Why it works
resample builds a regular calendar of periods first and then sums into it, so gaps appear as zeros instead of vanishing, which keeps month-to-month comparisons honest.
Examples
3 2024-01-05 10 2024-01-20 5 2024-03-02 7
2024-01 15.00 2024-02 0.00 2024-03 7.00 best 2024-01
2 2024-12-31 1 2025-01-01 2
2024-12 1.00 2025-01 2.00 best 2025-01
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Total the amounts per (year, month).
Hint 2
Walk month by month from the first to the last, adding 1 to the month and rolling over to January of the next year after December.
Hint 3
Months with no records have a total of 0.
Solution
Show one correct solution (try it yourself first)
n = int(input())
totals = {}
for _ in range(n):
d, amount = input().split()
key = (int(d[:4]), int(d[5:7]))
totals[key] = totals.get(key, 0) + float(amount)
y, m = min(totals)
last = max(totals)
best = None
while (y, m) <= last:
t = totals.get((y, m), 0)
print(f"{y}-{m:02d} {t:.2f}")
if best is None or t > best[0]:
best = (t, f"{y}-{m:02d}")
m += 1
if m == 13:
y, m = y + 1, 1
print("best", best[1])