Skip to content

Commit 1514002

Browse files
rhettingerpull[bot]
authored andcommitted
Modernize roundrobin() recipe and improve variable names (gh-116710)
1 parent a8489c1 commit 1514002

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed

Doc/library/itertools.rst

+14-17
Original file line numberDiff line numberDiff line change
@@ -932,31 +932,25 @@ which incur interpreter overhead.
932932
# grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
933933
# grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
934934
# grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
935-
args = [iter(iterable)] * n
935+
iterators = [iter(iterable)] * n
936936
match incomplete:
937937
case 'fill':
938-
return zip_longest(*args, fillvalue=fillvalue)
938+
return zip_longest(*iterators, fillvalue=fillvalue)
939939
case 'strict':
940-
return zip(*args, strict=True)
940+
return zip(*iterators, strict=True)
941941
case 'ignore':
942-
return zip(*args)
942+
return zip(*iterators)
943943
case _:
944944
raise ValueError('Expected fill, strict, or ignore')
945945
946946
def roundrobin(*iterables):
947947
"Visit input iterables in a cycle until each is exhausted."
948948
# roundrobin('ABC', 'D', 'EF') --> A D E B F C
949-
# Recipe credited to George Sakkis
950-
num_active = len(iterables)
951-
nexts = cycle(iter(it).__next__ for it in iterables)
952-
while num_active:
953-
try:
954-
for next in nexts:
955-
yield next()
956-
except StopIteration:
957-
# Remove the iterator we just exhausted from the cycle.
958-
num_active -= 1
959-
nexts = cycle(islice(nexts, num_active))
949+
# Algorithm credited to George Sakkis
950+
iterators = map(iter, iterables)
951+
for num_active in range(len(iterables), 0, -1):
952+
iterators = cycle(islice(iterators, num_active))
953+
yield from map(next, iterators)
960954
961955
def partition(predicate, iterable):
962956
"""Partition entries into false entries and true entries.
@@ -997,10 +991,10 @@ The following recipes have a more mathematical flavor:
997991
s = list(iterable)
998992
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
999993

1000-
def sum_of_squares(it):
994+
def sum_of_squares(iterable):
1001995
"Add up the squares of the input values."
1002996
# sum_of_squares([10, 20, 30]) --> 1400
1003-
return math.sumprod(*tee(it))
997+
return math.sumprod(*tee(iterable))
1004998
1005999
def reshape(matrix, cols):
10061000
"Reshape a 2-D matrix to have a given number of columns."
@@ -1570,6 +1564,9 @@ The following recipes have a more mathematical flavor:
15701564

15711565
>>> list(roundrobin('abc', 'd', 'ef'))
15721566
['a', 'd', 'e', 'b', 'f', 'c']
1567+
>>> ranges = [range(5, 1000), range(4, 3000), range(0), range(3, 2000), range(2, 5000), range(1, 3500)]
1568+
>>> collections.Counter(roundrobin(ranges)) == collections.Counter(ranges)
1569+
True
15731570

15741571
>>> def is_odd(x):
15751572
... return x % 2 == 1

0 commit comments

Comments
 (0)