summaryrefslogtreecommitdiff
path: root/Doc/library/collections.rst
diff options
context:
space:
mode:
authorRaymond Hettinger <rhettinger@users.noreply.github.com>2017-11-23 13:32:23 -0800
committerGitHub <noreply@github.com>2017-11-23 13:32:23 -0800
commit0858495a50e19defde786a4ec050ec182e920f46 (patch)
tree8cd15589e6173b0bcc20f760b47673e153390e93 /Doc/library/collections.rst
parentdcaed6b2d954786eb5369ec2e8dfdeefe3cdc6ae (diff)
downloadcpython-git-0858495a50e19defde786a4ec050ec182e920f46.tar.gz
bpo-32099 Add deque variant of roundrobin() recipe (#4497)
* Minor wording tweaks
Diffstat (limited to 'Doc/library/collections.rst')
-rw-r--r--Doc/library/collections.rst19
1 files changed, 19 insertions, 0 deletions
diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst
index cda829694a..4b0d8c048a 100644
--- a/Doc/library/collections.rst
+++ b/Doc/library/collections.rst
@@ -618,6 +618,25 @@ added elements by appending to the right and popping to the left::
d.append(elem)
yield s / n
+A `round-robin scheduler
+<https://en.wikipedia.org/wiki/Round-robin_scheduling>`_ can be implemented with
+input iterators stored in a :class:`deque`. Values are yielded from the active
+iterator in position zero. If that iterator is exhausted, it can be removed
+with :meth:`~deque.popleft`; otherwise, it can be cycled back to the end with
+the :meth:`~deque.rotate` method::
+
+ def roundrobin(*iterables):
+ "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
+ iterators = deque(map(iter, iterables))
+ while iterators:
+ try:
+ while True:
+ yield next(iterators[0])
+ iterators.rotate(-1)
+ except StopIteration:
+ # Remove an exhausted iterator.
+ iterators.popleft()
+
The :meth:`rotate` method provides a way to implement :class:`deque` slicing and
deletion. For example, a pure Python implementation of ``del d[n]`` relies on
the :meth:`rotate` method to position elements to be popped::