Skip to content

Instantly share code, notes, and snippets.

@telendt
Created April 24, 2017 10:12
Show Gist options
  • Save telendt/3fe7f3db9301d40cb3291c1d05428c21 to your computer and use it in GitHub Desktop.
Save telendt/3fe7f3db9301d40cb3291c1d05428c21 to your computer and use it in GitHub Desktop.
Merging iterators (coroutine)
def merge_two(i: Iterator[T], j: Iterator[T]) -> Iterator[T]:
"""
>>> list(merge_two(iter([1, 2, 4]), iter([0, 1, 3, 4])))
[0, 1, 1, 2, 3, 4, 4]
"""
try:
x = next(i)
except StopIteration:
yield from j
return
try:
y = next(j)
except StopIteration:
yield x
yield from i
return
while True:
if y > x:
yield x
try:
x = next(i)
except StopIteration:
yield y
yield from j
return
else:
yield y
try:
y = next(j)
except StopIteration:
yield x
yield from i
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment