Cohort 4Register

PART 2 · PYTHON FOUNDATIONS · BEFORE YOU CODE

The 6-step approach to any coding question

FreeLesson 23 of 78

Use this on every coding question in the book. DE interviewers grade how you get there almost as much as the code.

Watch it work on one question

Q6From orders.csv, return each customer's total delivered spend, highest first. Ties broken by customer_id.DEEASY

StepWhat you say in the interview
01 I/OIn: rows from orders.csv. Out: a list of (customer_id, total) tuples, highest total first.
02 EdgesAmounts arrive as strings. Some orders are cancelled or returned. A customer may have no delivered orders and should not appear.
03 BruteFor each customer, scan all orders: O(customers x orders). Fine for 15 rows, not for 15 million.
04 StructureOne pass with a defaultdict(Decimal) keyed by customer: O(n). Decimal because this is money (page 27).
05 Functionsload_rows reads and converts, delivered_totals aggregates, sorted ranks.
06 TestRun on the sample, check one total by hand (Aarav: 1198 + 1499 + 2397 = 5094), then say: O(n) to sum, O(k log k) to sort k customers.
SOLUTIONPYTHON 3.12
import csv
from collections import defaultdict
from decimal import Decimal

def load_rows(path):
    with open(path, newline="") as f:
        for row in csv.DictReader(f):
            row["customer_id"] = int(row["customer_id"])
            row["amount"] = Decimal(row["amount"])
            yield row

def delivered_totals(rows):
    totals = defaultdict(Decimal)
    for r in rows:
        if r["status"] == "delivered":
            totals[r["customer_id"]] += r["amount"]
    return totals

totals = delivered_totals(load_rows("orders.csv"))
ranked = sorted(totals.items(), key=lambda kv: (-kv[1], kv[0]))
for cid, total in ranked:
    print(cid, total)

Output

5 5096.00
1 5094.00
2 4143.00
6 1998.00
4 1048.00
7 846.00
3 747.00

Practice before you move on

  1. Walk the six steps for a new question: which customer in orders.csv has the most delivered orders?
  2. Write two edge cases that the worked solution must handle, and run them.