itertools — Functions creating iterators for efficient looping¶
This module implements a number ofiterator building blocks inspiredby constructs from APL, Haskell, and SML. Each has been recast in a formsuitable for Python.
The module standardizes a core set of fast, memory efficient tools that areuseful by themselves or in combination. Together, they form an “iteratoralgebra” making it possible to construct specialized tools succinctly andefficiently in pure Python.
For instance, SML provides a tabulation tool:tabulate(f) which produces asequencef(0),f(1),.... The same effect can be achieved in Pythonby combiningmap() andcount() to formmap(f,count()).
These tools and their built-in counterparts also work well with the high-speedfunctions in theoperator module. For example, the multiplicationoperator can be mapped across two vectors to form an efficient dot-product:sum(starmap(operator.mul,zip(vec1,vec2,strict=True))).
Infinite iterators:
Iterator | Arguments | Results | Example |
|---|---|---|---|
start, [step] | start, start+step, start+2*step, … |
| |
p | p0, p1, … plast, p0, p1, … |
| |
elem [,n] | elem, elem, elem, … endlessly or up to n times |
|
Iterators terminating on the shortest input sequence:
Iterator | Arguments | Results | Example |
|---|---|---|---|
p [,func] | p0, p0+p1, p0+p1+p2, … |
| |
p, q, … | p0, p1, … plast, q0, q1, … |
| |
iterable | p0, p1, … plast, q0, q1, … |
| |
data, selectors | (d[0] if s[0]), (d[1] if s[1]), … |
| |
pred, seq | seq[n], seq[n+1], starting when pred fails |
| |
pred, seq | elements of seq where pred(elem) is false |
| |
iterable[, key] | sub-iterators grouped by value of key(v) | ||
seq, [start,] stop [, step] | elements from seq[start:stop:step] |
| |
iterable | (p[0], p[1]), (p[1], p[2]) |
| |
func, seq | func(*seq[0]), func(*seq[1]), … |
| |
pred, seq | seq[0], seq[1], until pred fails |
| |
it, n | it1, it2, … itn splits one iterator into n | ||
p, q, … | (p[0], q[0]), (p[1], q[1]), … |
|
Combinatoric iterators:
Iterator | Arguments | Results |
|---|---|---|
p, q, … [repeat=1] | cartesian product, equivalent to a nested for-loop | |
p[, r] | r-length tuples, all possible orderings, no repeated elements | |
p, r | r-length tuples, in sorted order, no repeated elements | |
p, r | r-length tuples, in sorted order, with repeated elements |
Examples | Results |
|---|---|
|
|
|
|
|
|
|
|
Itertool functions¶
The following module functions all construct and return iterators. Some providestreams of infinite length, so they should only be accessed by functions orloops that truncate the stream.
- itertools.accumulate(iterable[,func,*,initial=None])¶
Make an iterator that returns accumulated sums, or accumulatedresults of other binary functions (specified via the optionalfunc argument).
Iffunc is supplied, it should be a functionof two arguments. Elements of the inputiterable may be any typethat can be accepted as arguments tofunc. (For example, withthe default operation of addition, elements may be any addabletype including
DecimalorFraction.)Usually, the number of elements output matches the input iterable.However, if the keyword argumentinitial is provided, theaccumulation leads off with theinitial value so that the outputhas one more element than the input iterable.
Roughly equivalent to:
defaccumulate(iterable,func=operator.add,*,initial=None):'Return running totals'# accumulate([1,2,3,4,5]) --> 1 3 6 10 15# accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115# accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120it=iter(iterable)total=initialifinitialisNone:try:total=next(it)exceptStopIteration:returnyieldtotalforelementinit:total=func(total,element)yieldtotal
There are a number of uses for thefunc argument. It can be set to
min()for a running minimum,max()for a running maximum, oroperator.mul()for a running product. Amortization tables can bebuilt by accumulating interest and applying payments:>>>data=[3,4,6,2,1,9,0,7,5,8]>>>list(accumulate(data,operator.mul))# running product[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]>>>list(accumulate(data,max))# running maximum[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]# Amortize a 5% loan of 1000 with 4 annual payments of 90>>>cashflows=[1000,-90,-90,-90,-90]>>>list(accumulate(cashflows,lambdabal,pmt:bal*1.05+pmt))[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]
See
functools.reduce()for a similar function that returns only thefinal accumulated value.New in version 3.2.
Changed in version 3.3:Added the optionalfunc parameter.
Changed in version 3.8:Added the optionalinitial parameter.
- itertools.chain(*iterables)¶
Make an iterator that returns elements from the first iterable until it isexhausted, then proceeds to the next iterable, until all of the iterables areexhausted. Used for treating consecutive sequences as a single sequence.Roughly equivalent to:
defchain(*iterables):# chain('ABC', 'DEF') --> A B C D E Fforitiniterables:forelementinit:yieldelement
- classmethodchain.from_iterable(iterable)¶
Alternate constructor for
chain(). Gets chained inputs from asingle iterable argument that is evaluated lazily. Roughly equivalent to:deffrom_iterable(iterables):# chain.from_iterable(['ABC', 'DEF']) --> A B C D E Fforitiniterables:forelementinit:yieldelement
- itertools.combinations(iterable,r)¶
Returnr length subsequences of elements from the inputiterable.
The combination tuples are emitted in lexicographic ordering according tothe order of the inputiterable. So, if the inputiterable is sorted,the output tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on theirvalue. So if the input elements are unique, there will be no repeatedvalues in each combination.
Roughly equivalent to:
defcombinations(iterable,r):# combinations('ABCD', 2) --> AB AC AD BC BD CD# combinations(range(4), 3) --> 012 013 023 123pool=tuple(iterable)n=len(pool)ifr>n:returnindices=list(range(r))yieldtuple(pool[i]foriinindices)whileTrue:foriinreversed(range(r)):ifindices[i]!=i+n-r:breakelse:returnindices[i]+=1forjinrange(i+1,r):indices[j]=indices[j-1]+1yieldtuple(pool[i]foriinindices)
The code for
combinations()can be also expressed as a subsequenceofpermutations()after filtering entries where the elements are notin sorted order (according to their position in the input pool):defcombinations(iterable,r):pool=tuple(iterable)n=len(pool)forindicesinpermutations(range(n),r):ifsorted(indices)==list(indices):yieldtuple(pool[i]foriinindices)
The number of items returned is
n!/r!/(n-r)!when0<=r<=nor zero whenr>n.
- itertools.combinations_with_replacement(iterable,r)¶
Returnr length subsequences of elements from the inputiterableallowing individual elements to be repeated more than once.
The combination tuples are emitted in lexicographic ordering according tothe order of the inputiterable. So, if the inputiterable is sorted,the output tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on theirvalue. So if the input elements are unique, the generated combinationswill also be unique.
Roughly equivalent to:
defcombinations_with_replacement(iterable,r):# combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CCpool=tuple(iterable)n=len(pool)ifnotnandr:returnindices=[0]*ryieldtuple(pool[i]foriinindices)whileTrue:foriinreversed(range(r)):ifindices[i]!=n-1:breakelse:returnindices[i:]=[indices[i]+1]*(r-i)yieldtuple(pool[i]foriinindices)
The code for
combinations_with_replacement()can be also expressed asa subsequence ofproduct()after filtering entries where the elementsare not in sorted order (according to their position in the input pool):defcombinations_with_replacement(iterable,r):pool=tuple(iterable)n=len(pool)forindicesinproduct(range(n),repeat=r):ifsorted(indices)==list(indices):yieldtuple(pool[i]foriinindices)
The number of items returned is
(n+r-1)!/r!/(n-1)!whenn>0.New in version 3.1.
- itertools.compress(data,selectors)¶
Make an iterator that filters elements fromdata returning only those thathave a corresponding element inselectors that evaluates to
True.Stops when either thedata orselectors iterables has been exhausted.Roughly equivalent to:defcompress(data,selectors):# compress('ABCDEF', [1,0,1,0,1,1]) --> A C E Freturn(dford,sinzip(data,selectors)ifs)
New in version 3.1.
- itertools.count(start=0,step=1)¶
Make an iterator that returns evenly spaced values starting with numberstart. Oftenused as an argument to
map()to generate consecutive data points.Also, used withzip()to add sequence numbers. Roughly equivalent to:defcount(start=0,step=1):# count(10) --> 10 11 12 13 14 ...# count(2.5, 0.5) --> 2.5 3.0 3.5 ...n=startwhileTrue:yieldnn+=step
When counting with floating point numbers, better accuracy can sometimes beachieved by substituting multiplicative code such as:
(start+step*iforiincount()).Changed in version 3.1:Addedstep argument and allowed non-integer arguments.
- itertools.cycle(iterable)¶
Make an iterator returning elements from the iterable and saving a copy of each.When the iterable is exhausted, return elements from the saved copy. Repeatsindefinitely. Roughly equivalent to:
defcycle(iterable):# cycle('ABCD') --> A B C D A B C D A B C D ...saved=[]forelementiniterable:yieldelementsaved.append(element)whilesaved:forelementinsaved:yieldelement
Note, this member of the toolkit may require significant auxiliary storage(depending on the length of the iterable).
- itertools.dropwhile(predicate,iterable)¶
Make an iterator that drops elements from the iterable as long as the predicateis true; afterwards, returns every element. Note, the iterator does not produceany output until the predicate first becomes false, so it may have a lengthystart-up time. Roughly equivalent to:
defdropwhile(predicate,iterable):# dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1iterable=iter(iterable)forxiniterable:ifnotpredicate(x):yieldxbreakforxiniterable:yieldx
- itertools.filterfalse(predicate,iterable)¶
Make an iterator that filters elements from iterable returning only those forwhich the predicate is false. Ifpredicate is
None, return the itemsthat are false. Roughly equivalent to:deffilterfalse(predicate,iterable):# filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8ifpredicateisNone:predicate=boolforxiniterable:ifnotpredicate(x):yieldx
- itertools.groupby(iterable,key=None)¶
Make an iterator that returns consecutive keys and groups from theiterable.Thekey is a function computing a key value for each element. If notspecified or is
None,key defaults to an identity function and returnsthe element unchanged. Generally, the iterable needs to already be sorted onthe same key function.The operation of
groupby()is similar to theuniqfilter in Unix. Itgenerates a break or new group every time the value of the key function changes(which is why it is usually necessary to have sorted the data using the same keyfunction). That behavior differs from SQL’s GROUP BY which aggregates commonelements regardless of their input order.The returned group is itself an iterator that shares the underlying iterablewith
groupby(). Because the source is shared, when thegroupby()object is advanced, the previous group is no longer visible. So, if that datais needed later, it should be stored as a list:groups=[]uniquekeys=[]data=sorted(data,key=keyfunc)fork,gingroupby(data,keyfunc):groups.append(list(g))# Store group iterator as a listuniquekeys.append(k)
groupby()is roughly equivalent to:classgroupby:# [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B# [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC Ddef__init__(self,iterable,key=None):ifkeyisNone:key=lambdax:xself.keyfunc=keyself.it=iter(iterable)self.tgtkey=self.currkey=self.currvalue=object()def__iter__(self):returnselfdef__next__(self):self.id=object()whileself.currkey==self.tgtkey:self.currvalue=next(self.it)# Exit on StopIterationself.currkey=self.keyfunc(self.currvalue)self.tgtkey=self.currkeyreturn(self.currkey,self._grouper(self.tgtkey,self.id))def_grouper(self,tgtkey,id):whileself.idisidandself.currkey==tgtkey:yieldself.currvaluetry:self.currvalue=next(self.it)exceptStopIteration:returnself.currkey=self.keyfunc(self.currvalue)
- itertools.islice(iterable,stop)¶
- itertools.islice(iterable,start,stop[,step])
Make an iterator that returns selected elements from the iterable. Ifstart isnon-zero, then elements from the iterable are skipped until start is reached.Afterward, elements are returned consecutively unlessstep is set higher thanone which results in items being skipped. Ifstop is
None, then iterationcontinues until the iterator is exhausted, if at all; otherwise, it stops at thespecified position.Ifstart is
None, then iteration starts at zero. Ifstep isNone,then the step defaults to one.Unlike regular slicing,
islice()does not support negative values forstart,stop, orstep. Can be used to extract related fields fromdata where the internal structure has been flattened (for example, amulti-line report may list a name field on every third line).Roughly equivalent to:
defislice(iterable,*args):# islice('ABCDEFG', 2) --> A B# islice('ABCDEFG', 2, 4) --> C D# islice('ABCDEFG', 2, None) --> C D E F G# islice('ABCDEFG', 0, None, 2) --> A C E Gs=slice(*args)start,stop,step=s.startor0,s.stoporsys.maxsize,s.stepor1it=iter(range(start,stop,step))try:nexti=next(it)exceptStopIteration:# Consume *iterable* up to the *start* position.fori,elementinzip(range(start),iterable):passreturntry:fori,elementinenumerate(iterable):ifi==nexti:yieldelementnexti=next(it)exceptStopIteration:# Consume to *stop*.fori,elementinzip(range(i+1,stop),iterable):pass
- itertools.pairwise(iterable)¶
Return successive overlapping pairs taken from the inputiterable.
The number of 2-tuples in the output iterator will be one fewer than thenumber of inputs. It will be empty if the input iterable has fewer thantwo values.
Roughly equivalent to:
defpairwise(iterable):# pairwise('ABCDEFG') --> AB BC CD DE EF FGa,b=tee(iterable)next(b,None)returnzip(a,b)
New in version 3.10.
- itertools.permutations(iterable,r=None)¶
Return successiver length permutations of elements in theiterable.
Ifr is not specified or is
None, thenr defaults to the lengthof theiterable and all possible full-length permutationsare generated.The permutation tuples are emitted in lexicographic order according tothe order of the inputiterable. So, if the inputiterable is sorted,the output tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on theirvalue. So if the input elements are unique, there will be no repeatedvalues within a permutation.
Roughly equivalent to:
defpermutations(iterable,r=None):# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC# permutations(range(3)) --> 012 021 102 120 201 210pool=tuple(iterable)n=len(pool)r=nifrisNoneelserifr>n:returnindices=list(range(n))cycles=list(range(n,n-r,-1))yieldtuple(pool[i]foriinindices[:r])whilen:foriinreversed(range(r)):cycles[i]-=1ifcycles[i]==0:indices[i:]=indices[i+1:]+indices[i:i+1]cycles[i]=n-ielse:j=cycles[i]indices[i],indices[-j]=indices[-j],indices[i]yieldtuple(pool[i]foriinindices[:r])breakelse:return
The code for
permutations()can be also expressed as a subsequence ofproduct(), filtered to exclude entries with repeated elements (thosefrom the same position in the input pool):defpermutations(iterable,r=None):pool=tuple(iterable)n=len(pool)r=nifrisNoneelserforindicesinproduct(range(n),repeat=r):iflen(set(indices))==r:yieldtuple(pool[i]foriinindices)
The number of items returned is
n!/(n-r)!when0<=r<=nor zero whenr>n.
- itertools.product(*iterables,repeat=1)¶
Cartesian product of input iterables.
Roughly equivalent to nested for-loops in a generator expression. For example,
product(A,B)returns the same as((x,y)forxinAforyinB).The nested loops cycle like an odometer with the rightmost element advancingon every iteration. This pattern creates a lexicographic ordering so that ifthe input’s iterables are sorted, the product tuples are emitted in sortedorder.
To compute the product of an iterable with itself, specify the number ofrepetitions with the optionalrepeat keyword argument. For example,
product(A,repeat=4)means the same asproduct(A,A,A,A).This function is roughly equivalent to the following code, except that theactual implementation does not build up intermediate results in memory:
defproduct(*args,repeat=1):# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111pools=[tuple(pool)forpoolinargs]*repeatresult=[[]]forpoolinpools:result=[x+[y]forxinresultforyinpool]forprodinresult:yieldtuple(prod)
Before
product()runs, it completely consumes the input iterables,keeping pools of values in memory to generate the products. Accordingly,it is only useful with finite inputs.
- itertools.repeat(object[,times])¶
Make an iterator that returnsobject over and over again. Runs indefinitelyunless thetimes argument is specified.
Roughly equivalent to:
defrepeat(object,times=None):# repeat(10, 3) --> 10 10 10iftimesisNone:whileTrue:yieldobjectelse:foriinrange(times):yieldobject
A common use forrepeat is to supply a stream of constant values tomaporzip:
>>>list(map(pow,range(10),repeat(2)))[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
- itertools.starmap(function,iterable)¶
Make an iterator that computes the function using arguments obtained fromthe iterable. Used instead of
map()when argument parameters are alreadygrouped in tuples from a single iterable (when the data has been“pre-zipped”).The difference between
map()andstarmap()parallels thedistinction betweenfunction(a,b)andfunction(*c). Roughlyequivalent to:defstarmap(function,iterable):# starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000forargsiniterable:yieldfunction(*args)
- itertools.takewhile(predicate,iterable)¶
Make an iterator that returns elements from the iterable as long as thepredicate is true. Roughly equivalent to:
deftakewhile(predicate,iterable):# takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4forxiniterable:ifpredicate(x):yieldxelse:break
- itertools.tee(iterable,n=2)¶
Returnn independent iterators from a single iterable.
The following Python code helps explain whattee does (although the actualimplementation is more complex and uses only a single underlyingFIFO queue):
deftee(iterable,n=2):it=iter(iterable)deques=[collections.deque()foriinrange(n)]defgen(mydeque):whileTrue:ifnotmydeque:# when the local deque is emptytry:newval=next(it)# fetch a new value andexceptStopIteration:returnfordindeques:# load it to all the dequesd.append(newval)yieldmydeque.popleft()returntuple(gen(d)fordindeques)
Once a
tee()has been created, the originaliterable should not beused anywhere else; otherwise, theiterable could get advanced withoutthe tee objects being informed.teeiterators are not threadsafe. ARuntimeErrormay beraised when using simultaneously iterators returned by the sametee()call, even if the originaliterable is threadsafe.This itertool may require significant auxiliary storage (depending on howmuch temporary data needs to be stored). In general, if one iterator usesmost or all of the data before another iterator starts, it is faster to use
list()instead oftee().
- itertools.zip_longest(*iterables,fillvalue=None)¶
Make an iterator that aggregates elements from each of the iterables. If theiterables are of uneven length, missing values are filled-in withfillvalue.Iteration continues until the longest iterable is exhausted. Roughly equivalent to:
defzip_longest(*args,fillvalue=None):# zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-iterators=[iter(it)foritinargs]num_active=len(iterators)ifnotnum_active:returnwhileTrue:values=[]fori,itinenumerate(iterators):try:value=next(it)exceptStopIteration:num_active-=1ifnotnum_active:returniterators[i]=repeat(fillvalue)value=fillvaluevalues.append(value)yieldtuple(values)
If one of the iterables is potentially infinite, then the
zip_longest()function should be wrapped with something that limits the number of calls(for exampleislice()ortakewhile()). If not specified,fillvalue defaults toNone.
Itertools Recipes¶
This section shows recipes for creating an extended toolset using the existingitertools as building blocks.
The primary purpose of the itertools recipes is educational. The recipes showvarious ways of thinking about individual tools — for example, thatchain.from_iterable is related to the concept of flattening. The recipesalso give ideas about ways that the tools can be combined — for example, howcompress() andrange() can work together. The recipes also show patternsfor using itertools with theoperator andcollections modules aswell as with the built-in itertools such asmap(),filter(),reversed(), andenumerate().
A secondary purpose of the recipes is to serve as an incubator. Theaccumulate(),compress(), andpairwise() itertools started out asrecipes. Currently, theiter_index() recipe is being tested to seewhether it proves its worth.
Substantially all of these recipes and many, many others can be installed fromthemore-itertools project foundon the Python Package Index:
python-mpipinstallmore-itertools
Many of the recipes offer the same high performance as the underlying toolset.Superior memory performance is kept by processing elements one at a timerather than bringing the whole iterable into memory all at once. Code volume iskept small by linking the tools together in a functional style which helpseliminate temporary variables. High speed is retained by preferring“vectorized” building blocks over the use of for-loops andgeneratorswhich incur interpreter overhead.
importcollectionsimportmathimportoperatorimportrandomdeftake(n,iterable):"Return first n items of the iterable as a list"returnlist(islice(iterable,n))defprepend(value,iterable):"Prepend a single value in front of an iterable"# prepend(1, [2, 3, 4]) --> 1 2 3 4returnchain([value],iterable)deftabulate(function,start=0):"Return function(0), function(1), ..."returnmap(function,count(start))deftail(n,iterable):"Return an iterator over the last n items"# tail(3, 'ABCDEFG') --> E F Greturniter(collections.deque(iterable,maxlen=n))defconsume(iterator,n=None):"Advance the iterator n-steps ahead. If n is None, consume entirely."# Use functions that consume iterators at C speed.ifnisNone:# feed the entire iterator into a zero-length dequecollections.deque(iterator,maxlen=0)else:# advance to the empty slice starting at position nnext(islice(iterator,n,n),None)defnth(iterable,n,default=None):"Returns the nth item or a default value"returnnext(islice(iterable,n,None),default)defall_equal(iterable):"Returns True if all the elements are equal to each other"g=groupby(iterable)returnnext(g,True)andnotnext(g,False)defquantify(iterable,pred=bool):"Count how many times the predicate is True"returnsum(map(pred,iterable))defncycles(iterable,n):"Returns the sequence elements n times"returnchain.from_iterable(repeat(tuple(iterable),n))defbatched(iterable,n):"Batch data into tuples of length n. The last batch may be shorter."# batched('ABCDEFG', 3) --> ABC DEF Gifn<1:raiseValueError('n must be at least one')it=iter(iterable)whilebatch:=tuple(islice(it,n)):yieldbatchdefgrouper(iterable,n,*,incomplete='fill',fillvalue=None):"Collect data into non-overlapping fixed-length chunks or blocks"# grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx# grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError# grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEFargs=[iter(iterable)]*nifincomplete=='fill':returnzip_longest(*args,fillvalue=fillvalue)ifincomplete=='strict':returnzip(*args,strict=True)ifincomplete=='ignore':returnzip(*args)else:raiseValueError('Expected fill, strict, or ignore')defsumprod(vec1,vec2):"Compute a sum of products."returnsum(starmap(operator.mul,zip(vec1,vec2,strict=True)))defsum_of_squares(it):"Add up the squares of the input values."# sum_of_squares([10, 20, 30]) -> 1400returnsumprod(*tee(it))deftranspose(it):"Swap the rows and columns of the input."# transpose([(1, 2, 3), (11, 22, 33)]) --> (1, 11) (2, 22) (3, 33)returnzip(*it,strict=True)defmatmul(m1,m2):"Multiply two matrices."# matmul([(7, 5), (3, 5)], [[2, 5], [7, 9]]) --> (49, 80), (41, 60)n=len(m2[0])returnbatched(starmap(sumprod,product(m1,transpose(m2))),n)defconvolve(signal,kernel):# See: https://betterexplained.com/articles/intuitive-convolution/# convolve(data, [0.25, 0.25, 0.25, 0.25]) --> Moving average (blur)# convolve(data, [1, -1]) --> 1st finite difference (1st derivative)# convolve(data, [1, -2, 1]) --> 2nd finite difference (2nd derivative)kernel=tuple(kernel)[::-1]n=len(kernel)window=collections.deque([0],maxlen=n)*nforxinchain(signal,repeat(0,n-1)):window.append(x)yieldsumprod(kernel,window)defpolynomial_from_roots(roots):"""Compute a polynomial's coefficients from its roots. (x - 5) (x + 4) (x - 3) expands to: x³ -4x² -17x + 60 """# polynomial_from_roots([5, -4, 3]) --> [1, -4, -17, 60]expansion=[1]forrinroots:expansion=convolve(expansion,(1,-r))returnlist(expansion)defpolynomial_eval(coefficients,x):"""Evaluate a polynomial at a specific value. Computes with better numeric stability than Horner's method. """# Evaluate x³ -4x² -17x + 60 at x = 2.5# polynomial_eval([1, -4, -17, 60], x=2.5) --> 8.125n=len(coefficients)ifn==0:returnx*0# coerce zero to the type of xpowers=map(pow,repeat(x),reversed(range(n)))returnsumprod(coefficients,powers)defiter_index(iterable,value,start=0):"Return indices where a value occurs in a sequence or iterable."# iter_index('AABCADEAF', 'A') --> 0 1 4 7try:seq_index=iterable.indexexceptAttributeError:# Slow path for general iterablesit=islice(iterable,start,None)i=start-1try:whileTrue:yield(i:=i+operator.indexOf(it,value)+1)exceptValueError:passelse:# Fast path for sequencesi=start-1try:whileTrue:yield(i:=seq_index(value,i+1))exceptValueError:passdefsieve(n):"Primes less than n"# sieve(30) --> 2 3 5 7 11 13 17 19 23 29data=bytearray((0,1))*(n//2)data[:3]=0,0,0limit=math.isqrt(n)+1forpincompress(range(limit),data):data[p*p:n:p+p]=bytes(len(range(p*p,n,p+p)))data[2]=1returniter_index(data,1)ifn>2elseiter([])deffactor(n):"Prime factors of n."# factor(99) --> 3 3 11forprimeinsieve(math.isqrt(n)+1):whileTrue:quotient,remainder=divmod(n,prime)ifremainder:breakyieldprimen=quotientifn==1:returnifn>1:yieldndefflatten(list_of_lists):"Flatten one level of nesting"returnchain.from_iterable(list_of_lists)defrepeatfunc(func,times=None,*args):"""Repeat calls to func with specified arguments. Example: repeatfunc(random.random) """iftimesisNone:returnstarmap(func,repeat(args))returnstarmap(func,repeat(args,times))deftriplewise(iterable):"Return overlapping triplets from an iterable"# triplewise('ABCDEFG') --> ABC BCD CDE DEF EFGfor(a,_),(b,c)inpairwise(pairwise(iterable)):yielda,b,cdefsliding_window(iterable,n):# sliding_window('ABCDEFG', 4) --> ABCD BCDE CDEF DEFGit=iter(iterable)window=collections.deque(islice(it,n),maxlen=n)iflen(window)==n:yieldtuple(window)forxinit:window.append(x)yieldtuple(window)defroundrobin(*iterables):"roundrobin('ABC', 'D', 'EF') --> A D E B F C"# Recipe credited to George Sakkisnum_active=len(iterables)nexts=cycle(iter(it).__next__foritiniterables)whilenum_active:try:fornextinnexts:yieldnext()exceptStopIteration:# Remove the iterator we just exhausted from the cycle.num_active-=1nexts=cycle(islice(nexts,num_active))defpartition(pred,iterable):"Use a predicate to partition entries into false entries and true entries"# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9t1,t2=tee(iterable)returnfilterfalse(pred,t1),filter(pred,t2)defbefore_and_after(predicate,it):""" Variant of takewhile() that allows complete access to the remainder of the iterator. >>> it = iter('ABCdEfGhI') >>> all_upper, remainder = before_and_after(str.isupper, it) >>> ''.join(all_upper) 'ABC' >>> ''.join(remainder) # takewhile() would lose the 'd' 'dEfGhI' Note that the first iterator must be fully consumed before the second iterator can generate valid results. """it=iter(it)transition=[]deftrue_iterator():foreleminit:ifpredicate(elem):yieldelemelse:transition.append(elem)returndefremainder_iterator():yield fromtransitionyield fromitreturntrue_iterator(),remainder_iterator()defsubslices(seq):"Return all contiguous non-empty subslices of a sequence"# subslices('ABCD') --> A AB ABC ABCD B BC BCD C CD Dslices=starmap(slice,combinations(range(len(seq)+1),2))returnmap(operator.getitem,repeat(seq),slices)defpowerset(iterable):"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"s=list(iterable)returnchain.from_iterable(combinations(s,r)forrinrange(len(s)+1))defunique_everseen(iterable,key=None):"List unique elements, preserving order. Remember all elements ever seen."# unique_everseen('AAAABBBCCDAABBB') --> A B C D# unique_everseen('ABBcCAD', str.lower) --> A B c Dseen=set()ifkeyisNone:forelementinfilterfalse(seen.__contains__,iterable):seen.add(element)yieldelement# For order preserving deduplication,# a faster but non-lazy solution is:# yield from dict.fromkeys(iterable)else:forelementiniterable:k=key(element)ifknotinseen:seen.add(k)yieldelement# For use cases that allow the last matching element to be returned,# a faster but non-lazy solution is:# t1, t2 = tee(iterable)# yield from dict(zip(map(key, t1), t2)).values()defunique_justseen(iterable,key=None):"List unique elements, preserving order. Remember only the element just seen."# unique_justseen('AAAABBBCCDAABBB') --> A B C D A B# unique_justseen('ABBcCAD', str.lower) --> A B c A Dreturnmap(next,map(operator.itemgetter(1),groupby(iterable,key)))defiter_except(func,exception,first=None):""" Call a function repeatedly until an exception is raised. Converts a call-until-exception interface to an iterator interface. Like builtins.iter(func, sentinel) but uses an exception instead of a sentinel to end the loop. Examples: iter_except(functools.partial(heappop, h), IndexError) # priority queue iterator iter_except(d.popitem, KeyError) # non-blocking dict iterator iter_except(d.popleft, IndexError) # non-blocking deque iterator iter_except(q.get_nowait, Queue.Empty) # loop over a producer Queue iter_except(s.pop, KeyError) # non-blocking set iterator """try:iffirstisnotNone:yieldfirst()# For database APIs needing an initial cast to db.first()whileTrue:yieldfunc()exceptexception:passdeffirst_true(iterable,default=False,pred=None):"""Returns the first true value in the iterable. If no true value is found, returns *default* If *pred* is not None, returns the first item for which pred(item) is true. """# first_true([a,b,c], x) --> a or b or c or x# first_true([a,b], x, f) --> a if f(a) else b if f(b) else xreturnnext(filter(pred,iterable),default)defnth_combination(iterable,r,index):"Equivalent to list(combinations(iterable, r))[index]"pool=tuple(iterable)n=len(pool)c=math.comb(n,r)ifindex<0:index+=cifindex<0orindex>=c:raiseIndexErrorresult=[]whiler:c,n,r=c*r//n,n-1,r-1whileindex>=c:index-=cc,n=c*(n-r)//n,n-1result.append(pool[-1-n])returntuple(result)