File tree Expand file tree Collapse file tree 1 file changed +19
-0
lines changed Expand file tree Collapse file tree 1 file changed +19
-0
lines changed Original file line number Diff line number Diff line change @@ -618,6 +618,25 @@ added elements by appending to the right and popping to the left::
618
618
d.append(elem)
619
619
yield s / n
620
620
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
+
621
640
The :meth: `rotate ` method provides a way to implement :class: `deque ` slicing and
622
641
deletion. For example, a pure Python implementation of ``del d[n] `` relies on
623
642
the :meth: `rotate ` method to position elements to be popped::
You can’t perform that action at this time.
0 commit comments