Write a round_robin(*iterables) generator that takes one item from each iterable in turn, dropping iterables as they run out, to interleave task queues.
from collections import deque
def round_robin(*iterables):
queue = deque(iter(it) for it in iterables)
while queue:
it = queue.popleft()
try:
yield next(it)
except StopIteration:
continue # this iterator is finished; do not put it back
queue.append(it)
web = ["W1", "W2", "W3"]
db = ["D1"]
mail = (f"M{i}" for i in range(1, 3))
print(list(round_robin(web, db, mail)))
Output Verified by running it on Python 3
['W1', 'D1', 'M1', 'W2', 'M2', 'W3']
The deque holds the live iterators; each one yields one item and goes to the back of the queue. Catching StopIteration from next() here is safe because it is handled before it can leave the generator.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!