runtime
358 / 500
question 358 Memory & Python Internals · medium

Total fares per zone in constant memory

A month of taxi trips arrives as an iterator of CSV lines (zone,fare_cents, header first): millions of lines, more than fit in memory. Write zone_totals(lines) that adds up the fares per pickup zone while holding only one line at a time. The hidden test feeds 200,000 lines and measures the peak memory with tracemalloc.

Functionzone_totals(lines)
linesan iterable of text lines; the first is the header zone,fare_cents, each other line is zone,cents (whole numbers)
Returnsa dictionary from zone (text) to total cents (int)
Constraintpeak memory below 200,000 bytes for 200,000 lines from a generator
Examples
callzone_totals(['zone,fare_cents', '186,4080', '264,720', '186,1720'])returns{'186': 5800, '264': 720}
callzone_totals(['zone,fare_cents'])returns{}
callzone_totals(['zone,fare_cents', '48,1550'])returns{'48': 1550}

Loading your progress…

Total fares per zone in constant memory — Python practice · Runtime