Created
April 24, 2017 10:12
-
-
Save telendt/3fe7f3db9301d40cb3291c1d05428c21 to your computer and use it in GitHub Desktop.
Merging iterators (coroutine)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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