@@ -932,31 +932,25 @@ which incur interpreter overhead.
932
932
# grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
933
933
# grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
934
934
# grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
935
- args = [iter(iterable)] * n
935
+ iterators = [iter(iterable)] * n
936
936
match incomplete:
937
937
case 'fill':
938
- return zip_longest(*args , fillvalue=fillvalue)
938
+ return zip_longest(*iterators , fillvalue=fillvalue)
939
939
case 'strict':
940
- return zip(*args , strict=True)
940
+ return zip(*iterators , strict=True)
941
941
case 'ignore':
942
- return zip(*args )
942
+ return zip(*iterators )
943
943
case _:
944
944
raise ValueError('Expected fill, strict, or ignore')
945
945
946
946
def roundrobin(*iterables):
947
947
"Visit input iterables in a cycle until each is exhausted."
948
948
# 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)
960
954
961
955
def partition(predicate, iterable):
962
956
"""Partition entries into false entries and true entries.
@@ -997,10 +991,10 @@ The following recipes have a more mathematical flavor:
997
991
s = list(iterable)
998
992
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
999
993
1000
- def sum_of_squares(it ):
994
+ def sum_of_squares(iterable ):
1001
995
"Add up the squares of the input values."
1002
996
# sum_of_squares([10, 20, 30]) --> 1400
1003
- return math.sumprod(*tee(it ))
997
+ return math.sumprod(*tee(iterable ))
1004
998
1005
999
def reshape(matrix, cols):
1006
1000
"Reshape a 2-D matrix to have a given number of columns."
@@ -1570,6 +1564,9 @@ The following recipes have a more mathematical flavor:
1570
1564
1571
1565
>>> list (roundrobin(' abc' , ' d' , ' ef' ))
1572
1566
['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
1573
1570
1574
1571
>>> def is_odd (x ):
1575
1572
... return x % 2 == 1
0 commit comments