heapq.merge yields values from already sorted inputs in order while retaining one candidate from each feed.
Python heapq.merge: combine sorted feeds without sorting every value again
Operation contract
Two bounded receipt feeds are sorted by integer timestamp. The merge returns a timestamp-ordered stream of pairs, then the fixture materializes it for display. The inputs stay unchanged. If a feed breaks its sorted contract, merge does not repair it and its output may be wrong; the wrapper rejects such a feed before yielding.
Failure and ownership boundary
The wrapper uses concrete lists so it can validate before a caller consumes any result. A real one-use stream cannot be fully validated without buffering or a staged failure policy. Python exercise: merge two sorted feeds and preserve left-first ties, Python iterators: exhaustion and repeatable collection ownership and Python heapq top-k: define ties before ranking frequencies connect the data-structure choices.
Working program
from heapq import merge
def merged_events(*feeds):
if len(feeds) > 4 or any(type(feed) is not list or len(feed) > 20 or any(type(row) is not tuple or len(row) != 2 or type(row[0]) is not int or type(row[1]) is not str for row in feed) or any(a[0] > b[0] for a, b in zip(feed, feed[1:])) for feed in feeds):
raise ValueError("sorted bounded feeds")
return list(merge(*feeds, key=lambda row: row[0]))
print(merged_events([(1, "R41"), (4, "R43")], [(2, "R42"), (5, "R44")]))
try:
merged_events([(3, "R43"), (1, "R41")])
except ValueError:
print("unsorted feed rejected")Output
[(1, 'R41'), (2, 'R42'), (4, 'R43'), (5, 'R44')]
unsorted feed rejectedCosts and limits
For n total items across k feeds, merging costs O(n log k) comparisons and O(k) heap storage. This wrapper materializes O(n) output and scans inputs for validation first.
Common Mistakes
- heapq.merge assumes every feed is sorted.
- Materializing the iterator removes its streaming-memory benefit.
Connected lessons
Python exercise: merge two sorted feeds and preserve left-first ties, Python iterators: exhaustion and repeatable collection ownership, Python heapq top-k: define ties before ranking frequencies.
