@@ -924,31 +924,25 @@ which incur interpreter overhead.
924
924
# grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
925
925
# grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
926
926
# grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
927
- args = [iter(iterable)] * n
927
+ iterators = [iter(iterable)] * n
928
928
match incomplete:
929
929
case 'fill':
930
- return zip_longest(*args , fillvalue=fillvalue)
930
+ return zip_longest(*iterators , fillvalue=fillvalue)
931
931
case 'strict':
932
- return zip(*args , strict=True)
932
+ return zip(*iterators , strict=True)
933
933
case 'ignore':
934
- return zip(*args )
934
+ return zip(*iterators )
935
935
case _:
936
936
raise ValueError('Expected fill, strict, or ignore')
937
937
938
938
def roundrobin(*iterables):
939
939
"Visit input iterables in a cycle until each is exhausted."
940
940
# 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)
952
946
953
947
def partition(predicate, iterable):
954
948
"""Partition entries into false entries and true entries.
@@ -989,10 +983,10 @@ The following recipes have a more mathematical flavor:
989
983
s = list(iterable)
990
984
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
991
985
992
- def sum_of_squares(it ):
986
+ def sum_of_squares(iterable ):
993
987
"Add up the squares of the input values."
994
988
# sum_of_squares([10, 20, 30]) --> 1400
995
- return math.sumprod(*tee(it ))
989
+ return math.sumprod(*tee(iterable ))
996
990
997
991
def reshape(matrix, cols):
998
992
"Reshape a 2-D matrix to have a given number of columns."
@@ -1558,6 +1552,9 @@ The following recipes have a more mathematical flavor:
1558
1552
1559
1553
>>> list (roundrobin(' abc' , ' d' , ' ef' ))
1560
1554
['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
1561
1558
1562
1559
>>> def is_odd (x ):
1563
1560
... return x % 2 == 1
0 commit comments