LearnFrenzy
Sign in Take a free test

Iterators and Generators · Iterators and Generators Coding Problems · Question 10

Round-robin scheduling of several iterators in Python Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

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.

Solution
main.py Run
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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links