Created
November 7, 2019 11:15
-
-
Save Xvezda/0bd342df80750b2c28d90088952b0958 to your computer and use it in GitHub Desktop.
Python roundrobin version 2-3 compatible implementation
This file contains 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
from __future__ import absolute_import | |
from __future__ import division | |
from __future__ import print_function | |
from __future__ import unicode_literals | |
import itertools | |
def roundrobin(*iterables): | |
# https://docs.python.org/3/library/itertools.html | |
"roundrobin('ABC', 'D', 'EF') --> A D E B F C" | |
# Recipe credited to George Sakkis | |
num_active = len(iterables) | |
if hasattr(iter([]), 'next'): | |
nexts = itertools.cycle(iter(it).next for it in iterables) | |
else: | |
nexts = itertools.cycle(iter(it).__next__ for it in iterables) | |
while num_active: | |
try: | |
for next_ in nexts: | |
yield next_() | |
except StopIteration: | |
# Remove the iterator we just exhausted from the cycle. | |
num_active -= 1 | |
nexts = itertools.cycle(itertools.islice(nexts, num_active)) | |
print(list(roundrobin('FOO', 'BAR'))) # ['F', 'B', 'O', 'A', 'O', 'R'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment