Sum 400,000 rows by region. The first version trips on a bad value, the second on a short row, the third finishes.
- Budget
- 20 s for every attempt together
- Versions
- v1: Reads every amount as a number. Fails on the row that says n/a. v2: Skips amounts that are not numbers. Still fails on the row with a missing column. v3: Skips bad amounts and short rows, then reports totals per region.
import csv, io, random
# A sales export with 400,000 rows, generated the same way on every run (seed 7).
random.seed(7)
REGIONS = ["north", "south", "east", "west"]
rows = ["order_id,region,amount"]
for i in range(1, 400_001):
rows.append(f"{i},{random.choice(REGIONS)},{random.randint(100, 99_999) / 100}")
rows[250_000] = "250000,south,n/a" # a malformed amount
rows[320_000] = "320000,east" # a row with a missing column
text = "\n".join(rows)
total = 0.0
for line, row in enumerate(csv.DictReader(io.StringIO(text)), start=2):
total += float(row["amount"])
print(f"rows read: {line - 1:,} total: {total:,.2f}")