23. A Generator Pipeline
Difficulty: Medium · Topic: Generators & iterators
Click-stream lines look like "user,action,ms". Write two generators and a function that chains them:
parse(lines)yields a dict{'user': ..., 'action': ..., 'ms': int}per good line. Skip blank lines, lines starting with#, lines without exactly 3 comma-separated fields, and lines whosemsis not a whole number. Strip spaces around fields.slow(events, threshold)yields the events whosemsis at leastthreshold.pipeline(lines, threshold)returnsslow(parse(lines), threshold), lazily: the input can be an endless stream.
Your code runs in CPython on our servers against 5 tests, including hidden ones.
Sample test
lines = ["# user,action,ms", "asha,click,120", "ben,view,40", "", "chitra,click,300"]
list(pipeline(lines, 100))Expected: [{'user': 'asha', 'action': 'click', 'ms': 120}, {'user': 'chitra', 'action': 'click', 'ms': 300}]
Hints
Hint 1
Each stage takes an iterable and yields: stages chain like Unix pipes.Hint 2
int(" 42 ") works; int("4.2") and int("x") raise ValueError, which you can catch to skip the line.Hint 3
Compare numbers, not strings:"99" >= "100" is True.Learn the concepts
- Generators and lazy evaluation · 6 min read. yield, constant-memory pipelines, endless inputs and the one-pass rule.
- Iterators, yield from and itertools · 8 min read. The iterator protocol, re-iterable classes, recursive generators and the itertools you will use.
More Python problems
- Read a File in Chunks · Easy
- Batch an Iterable · Easy
- Moving Average over a Stream · Medium
- Flatten Any Iterable Lazily · Medium
- A Re-iterable Date Range · Medium
- Merge Sorted Streams Lazily · Hard