Skip to content

Commit e5c1456

Browse files
[3.12] Modernize roundrobin() recipe and improve variable names (gh-116710) (gh-116711)
1 parent 96c7604 commit e5c1456

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed

Doc/library/itertools.rst

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -924,31 +924,25 @@ which incur interpreter overhead.
924924
# grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
925925
# grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
926926
# grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
927-
args = [iter(iterable)] * n
927+
iterators = [iter(iterable)] * n
928928
match incomplete:
929929
case 'fill':
930-
return zip_longest(*args, fillvalue=fillvalue)
930+
return zip_longest(*iterators, fillvalue=fillvalue)
931931
case 'strict':
932-
return zip(*args, strict=True)
932+
return zip(*iterators, strict=True)
933933
case 'ignore':
934-
return zip(*args)
934+
return zip(*iterators)
935935
case _:
936936
raise ValueError('Expected fill, strict, or ignore')
937937
938938
def roundrobin(*iterables):
939939
"Visit input iterables in a cycle until each is exhausted."
940940
# roundrobin('ABC', 'D', 'EF') --> A D E B F C
941-
# Recipe credited to George Sakkis
942-
num_active = len(iterables)
943-
nexts = cycle(iter(it).__next__ for it in iterables)
944-
while num_active:
945-
try:
946-
for next in nexts:
947-
yield next()
948-
except StopIteration:
949-
# Remove the iterator we just exhausted from the cycle.
950-
num_active -= 1
951-
nexts = cycle(islice(nexts, num_active))
941+
# Algorithm credited to George Sakkis
942+
iterators = map(iter, iterables)
943+
for num_active in range(len(iterables), 0, -1):
944+
iterators = cycle(islice(iterators, num_active))
945+
yield from map(next, iterators)
952946
953947
def partition(predicate, iterable):
954948
"""Partition entries into false entries and true entries.
@@ -989,10 +983,10 @@ The following recipes have a more mathematical flavor:
989983
s = list(iterable)
990984
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
991985

992-
def sum_of_squares(it):
986+
def sum_of_squares(iterable):
993987
"Add up the squares of the input values."
994988
# sum_of_squares([10, 20, 30]) --> 1400
995-
return math.sumprod(*tee(it))
989+
return math.sumprod(*tee(iterable))
996990
997991
def reshape(matrix, cols):
998992
"Reshape a 2-D matrix to have a given number of columns."
@@ -1558,6 +1552,9 @@ The following recipes have a more mathematical flavor:
15581552

15591553
>>> list(roundrobin('abc', 'd', 'ef'))
15601554
['a', 'd', 'e', 'b', 'f', 'c']
1555+
>>> ranges = [range(5, 1000), range(4, 3000), range(0), range(3, 2000), range(2, 5000), range(1, 3500)]
1556+
>>> collections.Counter(roundrobin(ranges)) == collections.Counter(ranges)
1557+
True
15611558

15621559
>>> def is_odd(x):
15631560
... return x % 2 == 1

0 commit comments

Comments
 (0)