Single sales arrive in any order. Turn them into monthly totals in time order, with the growth from each month to the next.
What to build
A program that totals amounts per month and prints the percentage change.
Requirements
- Print one line per month that has data, in time order:
YYYY-MM TOTAL, with the total to two decimals. - From the second month on, add a space and the percentage change from the previous printed month, with its sign and one decimal place, followed by
%.
Input
Line 1: n. Then n lines YYYY-MM-DD AMOUNT.
Output
One line per month.
Constraints
1 ≤ n ≤ 1000; amounts are over 0.
Example
Input:
5
2024-01-05 100
2024-01-20 50
2024-02-03 180
2024-03-15 90
2024-03-01 45
Output:
2024-01 150.00
2024-02 180.00 +20.0%
2024-03 135.00 -25.0%
Why it works
Grouping by the YYYY-MM prefix aggregates each month, sorting the prefixes puts months in time order, and each change divides the difference by the earlier month's total.
Examples
Example 1 · Input
5 2024-01-05 100 2024-01-20 50 2024-02-03 180 2024-03-15 90 2024-03-01 45
Expected output
2024-01 150.00 2024-02 180.00 +20.0% 2024-03 135.00 -25.0%
Example 2 · Input
2 2024-01-01 10 2023-12-31 10
Expected output
2023-12 10.00 2024-01 10.00 +0.0%
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The month of a date YYYY-MM-DD is date[:7].
Hint 2
Sort the months; YYYY-MM strings sort in time order.
Hint 3
f"{change:+.1f}%" prints the sign.
Solution
Show one correct solution (try it yourself first)
n = int(input())
totals = {}
for _ in range(n):
date, amount = input().split()
totals[date[:7]] = totals.get(date[:7], 0) + float(amount)
prev = None
for month in sorted(totals):
line = f"{month} {totals[month]:.2f}"
if prev is not None:
line += f" {(totals[month] - prev) / prev * 100:+.1f}%"
print(line)
prev = totals[month]