Skip to content

Commit 0858495

Browse files
authored
bpo-32099 Add deque variant of roundrobin() recipe (#4497)
* Minor wording tweaks
1 parent dcaed6b commit 0858495

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

Doc/library/collections.rst

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,25 @@ added elements by appending to the right and popping to the left::
618618
d.append(elem)
619619
yield s / n
620620

621+
A `round-robin scheduler
622+
<https://en.wikipedia.org/wiki/Round-robin_scheduling>`_ can be implemented with
623+
input iterators stored in a :class:`deque`. Values are yielded from the active
624+
iterator in position zero. If that iterator is exhausted, it can be removed
625+
with :meth:`~deque.popleft`; otherwise, it can be cycled back to the end with
626+
the :meth:`~deque.rotate` method::
627+
628+
def roundrobin(*iterables):
629+
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
630+
iterators = deque(map(iter, iterables))
631+
while iterators:
632+
try:
633+
while True:
634+
yield next(iterators[0])
635+
iterators.rotate(-1)
636+
except StopIteration:
637+
# Remove an exhausted iterator.
638+
iterators.popleft()
639+
621640
The :meth:`rotate` method provides a way to implement :class:`deque` slicing and
622641
deletion. For example, a pure Python implementation of ``del d[n]`` relies on
623642
the :meth:`rotate` method to position elements to be popped::

0 commit comments

Comments
 (0)