Exercise: Merge sorted streams
Merging sorted inputs is the heart of merge sort, of database joins, and of "merge k sorted lists", a very common interview question.
Exercise: write merge, a generator that takes two sorted iterables
and yields all their items in sorted order.
list(merge([1, 4, 9], [2, 3, 10])) # [1, 2, 3, 4, 9, 10]
- Work lazily, one item at a time. Don't build lists, don't call
sorted. The inputs may be endless streams. - Keep the current front item of each input. Yield the smaller one and pull the next item from that input.
next(it, None)doesn't work as an "end" marker ifNonecould be an item. A privateDONE = object()sentinel is safer.- When one input runs out,
yield fromthe rest of the other.
Each item is handled once, so this is O(n). For more than two inputs,
heapq.merge does the same with a heap.
Press Check to run the tests.