Model df.groupby("customer").agg(orders=("amount", "size"), total=("amount", "sum"), first=("date", "min"), last=("date", "max")) and rank the customers.
What to build
A program that summarises orders per customer.
Requirements
- For each customer print
NAME: orders N, total T, FIRST to LAST, D days, with T to two decimals, FIRST and LAST the earliest and latest order dates and D the days between them; sort by total from largest to smallest, then by name. - Finally print
repeat customers K, the number of customers with at least two orders.
Input
Line 1: n. Then n lines CUSTOMER,YYYY-MM-DD,AMOUNT, in any order.
Output
One line per customer, then one line.
Constraints
1 ≤ n ≤ 1000; dates are valid.
Example
Input:
5
ana,2024-01-05,20
ben,2024-02-01,50
ana,2024-03-10,30
cy,2024-01-20,15
ben,2024-02-01,5
Output:
ben: orders 2, total 55.00, 2024-02-01 to 2024-02-01, 0 days
ana: orders 2, total 50.00, 2024-01-05 to 2024-03-10, 65 days
cy: orders 1, total 15.00, 2024-01-20 to 2024-01-20, 0 days
repeat customers 2
Why it works
Grouping collects every order of a customer together, so the count, sum, minimum and maximum come from the same rows, and subtracting real dates gives the number of days between the first and last order across month ends and leap years.
Examples
5 ana,2024-01-05,20 ben,2024-02-01,50 ana,2024-03-10,30 cy,2024-01-20,15 ben,2024-02-01,5
ben: orders 2, total 55.00, 2024-02-01 to 2024-02-01, 0 days ana: orders 2, total 50.00, 2024-01-05 to 2024-03-10, 65 days cy: orders 1, total 15.00, 2024-01-20 to 2024-01-20, 0 days repeat customers 2
1 x,2023-12-31,9.5
x: orders 1, total 9.50, 2023-12-31 to 2023-12-31, 0 days repeat customers 0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Group the orders by customer: count them, add the amounts and keep the earliest and latest date.
Hint 2
ISO dates compare correctly as text, and date.fromisoformat turns them into dates for subtraction.
Hint 3
Sort by total from largest to smallest, then by name.
Solution
Show one correct solution (try it yourself first)
from datetime import date
n = int(input())
first, last, count, total = {}, {}, {}, {}
for _ in range(n):
c, d, a = input().split(",")
first[c] = min(first.get(c, d), d)
last[c] = max(last.get(c, d), d)
count[c] = count.get(c, 0) + 1
total[c] = total.get(c, 0) + float(a)
for c in sorted(total, key=lambda c: (-total[c], c)):
days = (date.fromisoformat(last[c]) - date.fromisoformat(first[c])).days
print(f"{c}: orders {count[c]}, total {total[c]:.2f}, {first[c]} to {last[c]}, {days} days")
print("repeat customers", sum(1 for c in count if count[c] >= 2))