more.py 145 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806
  1. import math
  2. import warnings
  3. from collections import Counter, defaultdict, deque, abc
  4. from collections.abc import Sequence
  5. from functools import cached_property, partial, reduce, wraps
  6. from heapq import heapify, heapreplace, heappop
  7. from itertools import (
  8. chain,
  9. combinations,
  10. compress,
  11. count,
  12. cycle,
  13. dropwhile,
  14. groupby,
  15. islice,
  16. repeat,
  17. starmap,
  18. takewhile,
  19. tee,
  20. zip_longest,
  21. product,
  22. )
  23. from math import comb, e, exp, factorial, floor, fsum, log, perm, tau
  24. from queue import Empty, Queue
  25. from random import random, randrange, uniform
  26. from operator import itemgetter, mul, sub, gt, lt, ge, le
  27. from sys import hexversion, maxsize
  28. from time import monotonic
  29. from .recipes import (
  30. _marker,
  31. _zip_equal,
  32. UnequalIterablesError,
  33. consume,
  34. flatten,
  35. pairwise,
  36. powerset,
  37. take,
  38. unique_everseen,
  39. all_equal,
  40. batched,
  41. )
  42. __all__ = [
  43. 'AbortThread',
  44. 'SequenceView',
  45. 'UnequalIterablesError',
  46. 'adjacent',
  47. 'all_unique',
  48. 'always_iterable',
  49. 'always_reversible',
  50. 'bucket',
  51. 'callback_iter',
  52. 'chunked',
  53. 'chunked_even',
  54. 'circular_shifts',
  55. 'collapse',
  56. 'combination_index',
  57. 'combination_with_replacement_index',
  58. 'consecutive_groups',
  59. 'constrained_batches',
  60. 'consumer',
  61. 'count_cycle',
  62. 'countable',
  63. 'dft',
  64. 'difference',
  65. 'distinct_combinations',
  66. 'distinct_permutations',
  67. 'distribute',
  68. 'divide',
  69. 'doublestarmap',
  70. 'duplicates_everseen',
  71. 'duplicates_justseen',
  72. 'classify_unique',
  73. 'exactly_n',
  74. 'filter_except',
  75. 'filter_map',
  76. 'first',
  77. 'gray_product',
  78. 'groupby_transform',
  79. 'ichunked',
  80. 'iequals',
  81. 'idft',
  82. 'ilen',
  83. 'interleave',
  84. 'interleave_evenly',
  85. 'interleave_longest',
  86. 'intersperse',
  87. 'is_sorted',
  88. 'islice_extended',
  89. 'iterate',
  90. 'iter_suppress',
  91. 'join_mappings',
  92. 'last',
  93. 'locate',
  94. 'longest_common_prefix',
  95. 'lstrip',
  96. 'make_decorator',
  97. 'map_except',
  98. 'map_if',
  99. 'map_reduce',
  100. 'mark_ends',
  101. 'minmax',
  102. 'nth_or_last',
  103. 'nth_permutation',
  104. 'nth_product',
  105. 'nth_combination_with_replacement',
  106. 'numeric_range',
  107. 'one',
  108. 'only',
  109. 'outer_product',
  110. 'padded',
  111. 'partial_product',
  112. 'partitions',
  113. 'peekable',
  114. 'permutation_index',
  115. 'powerset_of_sets',
  116. 'product_index',
  117. 'raise_',
  118. 'repeat_each',
  119. 'repeat_last',
  120. 'replace',
  121. 'rlocate',
  122. 'rstrip',
  123. 'run_length',
  124. 'sample',
  125. 'seekable',
  126. 'set_partitions',
  127. 'side_effect',
  128. 'sliced',
  129. 'sort_together',
  130. 'split_after',
  131. 'split_at',
  132. 'split_before',
  133. 'split_into',
  134. 'split_when',
  135. 'spy',
  136. 'stagger',
  137. 'strip',
  138. 'strictly_n',
  139. 'substrings',
  140. 'substrings_indexes',
  141. 'takewhile_inclusive',
  142. 'time_limited',
  143. 'unique_in_window',
  144. 'unique_to_each',
  145. 'unzip',
  146. 'value_chain',
  147. 'windowed',
  148. 'windowed_complete',
  149. 'with_iter',
  150. 'zip_broadcast',
  151. 'zip_equal',
  152. 'zip_offset',
  153. ]
  154. # math.sumprod is available for Python 3.12+
  155. _fsumprod = getattr(math, 'sumprod', lambda x, y: fsum(map(mul, x, y)))
  156. def chunked(iterable, n, strict=False):
  157. """Break *iterable* into lists of length *n*:
  158. >>> list(chunked([1, 2, 3, 4, 5, 6], 3))
  159. [[1, 2, 3], [4, 5, 6]]
  160. By the default, the last yielded list will have fewer than *n* elements
  161. if the length of *iterable* is not divisible by *n*:
  162. >>> list(chunked([1, 2, 3, 4, 5, 6, 7, 8], 3))
  163. [[1, 2, 3], [4, 5, 6], [7, 8]]
  164. To use a fill-in value instead, see the :func:`grouper` recipe.
  165. If the length of *iterable* is not divisible by *n* and *strict* is
  166. ``True``, then ``ValueError`` will be raised before the last
  167. list is yielded.
  168. """
  169. iterator = iter(partial(take, n, iter(iterable)), [])
  170. if strict:
  171. if n is None:
  172. raise ValueError('n must not be None when using strict mode.')
  173. def ret():
  174. for chunk in iterator:
  175. if len(chunk) != n:
  176. raise ValueError('iterable is not divisible by n.')
  177. yield chunk
  178. return iter(ret())
  179. else:
  180. return iterator
  181. def first(iterable, default=_marker):
  182. """Return the first item of *iterable*, or *default* if *iterable* is
  183. empty.
  184. >>> first([0, 1, 2, 3])
  185. 0
  186. >>> first([], 'some default')
  187. 'some default'
  188. If *default* is not provided and there are no items in the iterable,
  189. raise ``ValueError``.
  190. :func:`first` is useful when you have a generator of expensive-to-retrieve
  191. values and want any arbitrary one. It is marginally shorter than
  192. ``next(iter(iterable), default)``.
  193. """
  194. for item in iterable:
  195. return item
  196. if default is _marker:
  197. raise ValueError(
  198. 'first() was called on an empty iterable, and no '
  199. 'default value was provided.'
  200. )
  201. return default
  202. def last(iterable, default=_marker):
  203. """Return the last item of *iterable*, or *default* if *iterable* is
  204. empty.
  205. >>> last([0, 1, 2, 3])
  206. 3
  207. >>> last([], 'some default')
  208. 'some default'
  209. If *default* is not provided and there are no items in the iterable,
  210. raise ``ValueError``.
  211. """
  212. try:
  213. if isinstance(iterable, Sequence):
  214. return iterable[-1]
  215. # Work around https://bugs.python.org/issue38525
  216. elif hasattr(iterable, '__reversed__') and (hexversion != 0x030800F0):
  217. return next(reversed(iterable))
  218. else:
  219. return deque(iterable, maxlen=1)[-1]
  220. except (IndexError, TypeError, StopIteration):
  221. if default is _marker:
  222. raise ValueError(
  223. 'last() was called on an empty iterable, and no default was '
  224. 'provided.'
  225. )
  226. return default
  227. def nth_or_last(iterable, n, default=_marker):
  228. """Return the nth or the last item of *iterable*,
  229. or *default* if *iterable* is empty.
  230. >>> nth_or_last([0, 1, 2, 3], 2)
  231. 2
  232. >>> nth_or_last([0, 1], 2)
  233. 1
  234. >>> nth_or_last([], 0, 'some default')
  235. 'some default'
  236. If *default* is not provided and there are no items in the iterable,
  237. raise ``ValueError``.
  238. """
  239. return last(islice(iterable, n + 1), default=default)
  240. class peekable:
  241. """Wrap an iterator to allow lookahead and prepending elements.
  242. Call :meth:`peek` on the result to get the value that will be returned
  243. by :func:`next`. This won't advance the iterator:
  244. >>> p = peekable(['a', 'b'])
  245. >>> p.peek()
  246. 'a'
  247. >>> next(p)
  248. 'a'
  249. Pass :meth:`peek` a default value to return that instead of raising
  250. ``StopIteration`` when the iterator is exhausted.
  251. >>> p = peekable([])
  252. >>> p.peek('hi')
  253. 'hi'
  254. peekables also offer a :meth:`prepend` method, which "inserts" items
  255. at the head of the iterable:
  256. >>> p = peekable([1, 2, 3])
  257. >>> p.prepend(10, 11, 12)
  258. >>> next(p)
  259. 10
  260. >>> p.peek()
  261. 11
  262. >>> list(p)
  263. [11, 12, 1, 2, 3]
  264. peekables can be indexed. Index 0 is the item that will be returned by
  265. :func:`next`, index 1 is the item after that, and so on:
  266. The values up to the given index will be cached.
  267. >>> p = peekable(['a', 'b', 'c', 'd'])
  268. >>> p[0]
  269. 'a'
  270. >>> p[1]
  271. 'b'
  272. >>> next(p)
  273. 'a'
  274. Negative indexes are supported, but be aware that they will cache the
  275. remaining items in the source iterator, which may require significant
  276. storage.
  277. To check whether a peekable is exhausted, check its truth value:
  278. >>> p = peekable(['a', 'b'])
  279. >>> if p: # peekable has items
  280. ... list(p)
  281. ['a', 'b']
  282. >>> if not p: # peekable is exhausted
  283. ... list(p)
  284. []
  285. """
  286. def __init__(self, iterable):
  287. self._it = iter(iterable)
  288. self._cache = deque()
  289. def __iter__(self):
  290. return self
  291. def __bool__(self):
  292. try:
  293. self.peek()
  294. except StopIteration:
  295. return False
  296. return True
  297. def peek(self, default=_marker):
  298. """Return the item that will be next returned from ``next()``.
  299. Return ``default`` if there are no items left. If ``default`` is not
  300. provided, raise ``StopIteration``.
  301. """
  302. if not self._cache:
  303. try:
  304. self._cache.append(next(self._it))
  305. except StopIteration:
  306. if default is _marker:
  307. raise
  308. return default
  309. return self._cache[0]
  310. def prepend(self, *items):
  311. """Stack up items to be the next ones returned from ``next()`` or
  312. ``self.peek()``. The items will be returned in
  313. first in, first out order::
  314. >>> p = peekable([1, 2, 3])
  315. >>> p.prepend(10, 11, 12)
  316. >>> next(p)
  317. 10
  318. >>> list(p)
  319. [11, 12, 1, 2, 3]
  320. It is possible, by prepending items, to "resurrect" a peekable that
  321. previously raised ``StopIteration``.
  322. >>> p = peekable([])
  323. >>> next(p)
  324. Traceback (most recent call last):
  325. ...
  326. StopIteration
  327. >>> p.prepend(1)
  328. >>> next(p)
  329. 1
  330. >>> next(p)
  331. Traceback (most recent call last):
  332. ...
  333. StopIteration
  334. """
  335. self._cache.extendleft(reversed(items))
  336. def __next__(self):
  337. if self._cache:
  338. return self._cache.popleft()
  339. return next(self._it)
  340. def _get_slice(self, index):
  341. # Normalize the slice's arguments
  342. step = 1 if (index.step is None) else index.step
  343. if step > 0:
  344. start = 0 if (index.start is None) else index.start
  345. stop = maxsize if (index.stop is None) else index.stop
  346. elif step < 0:
  347. start = -1 if (index.start is None) else index.start
  348. stop = (-maxsize - 1) if (index.stop is None) else index.stop
  349. else:
  350. raise ValueError('slice step cannot be zero')
  351. # If either the start or stop index is negative, we'll need to cache
  352. # the rest of the iterable in order to slice from the right side.
  353. if (start < 0) or (stop < 0):
  354. self._cache.extend(self._it)
  355. # Otherwise we'll need to find the rightmost index and cache to that
  356. # point.
  357. else:
  358. n = min(max(start, stop) + 1, maxsize)
  359. cache_len = len(self._cache)
  360. if n >= cache_len:
  361. self._cache.extend(islice(self._it, n - cache_len))
  362. return list(self._cache)[index]
  363. def __getitem__(self, index):
  364. if isinstance(index, slice):
  365. return self._get_slice(index)
  366. cache_len = len(self._cache)
  367. if index < 0:
  368. self._cache.extend(self._it)
  369. elif index >= cache_len:
  370. self._cache.extend(islice(self._it, index + 1 - cache_len))
  371. return self._cache[index]
  372. def consumer(func):
  373. """Decorator that automatically advances a PEP-342-style "reverse iterator"
  374. to its first yield point so you don't have to call ``next()`` on it
  375. manually.
  376. >>> @consumer
  377. ... def tally():
  378. ... i = 0
  379. ... while True:
  380. ... print('Thing number %s is %s.' % (i, (yield)))
  381. ... i += 1
  382. ...
  383. >>> t = tally()
  384. >>> t.send('red')
  385. Thing number 0 is red.
  386. >>> t.send('fish')
  387. Thing number 1 is fish.
  388. Without the decorator, you would have to call ``next(t)`` before
  389. ``t.send()`` could be used.
  390. """
  391. @wraps(func)
  392. def wrapper(*args, **kwargs):
  393. gen = func(*args, **kwargs)
  394. next(gen)
  395. return gen
  396. return wrapper
  397. def ilen(iterable):
  398. """Return the number of items in *iterable*.
  399. >>> ilen(x for x in range(1000000) if x % 3 == 0)
  400. 333334
  401. This consumes the iterable, so handle with care.
  402. """
  403. # This approach was selected because benchmarks showed it's likely the
  404. # fastest of the known implementations at the time of writing.
  405. # See GitHub tracker: #236, #230.
  406. counter = count()
  407. deque(zip(iterable, counter), maxlen=0)
  408. return next(counter)
  409. def iterate(func, start):
  410. """Return ``start``, ``func(start)``, ``func(func(start))``, ...
  411. >>> from itertools import islice
  412. >>> list(islice(iterate(lambda x: 2*x, 1), 10))
  413. [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
  414. """
  415. while True:
  416. yield start
  417. try:
  418. start = func(start)
  419. except StopIteration:
  420. break
  421. def with_iter(context_manager):
  422. """Wrap an iterable in a ``with`` statement, so it closes once exhausted.
  423. For example, this will close the file when the iterator is exhausted::
  424. upper_lines = (line.upper() for line in with_iter(open('foo')))
  425. Any context manager which returns an iterable is a candidate for
  426. ``with_iter``.
  427. """
  428. with context_manager as iterable:
  429. yield from iterable
  430. def one(iterable, too_short=None, too_long=None):
  431. """Return the first item from *iterable*, which is expected to contain only
  432. that item. Raise an exception if *iterable* is empty or has more than one
  433. item.
  434. :func:`one` is useful for ensuring that an iterable contains only one item.
  435. For example, it can be used to retrieve the result of a database query
  436. that is expected to return a single row.
  437. If *iterable* is empty, ``ValueError`` will be raised. You may specify a
  438. different exception with the *too_short* keyword:
  439. >>> it = []
  440. >>> one(it) # doctest: +IGNORE_EXCEPTION_DETAIL
  441. Traceback (most recent call last):
  442. ...
  443. ValueError: too many items in iterable (expected 1)'
  444. >>> too_short = IndexError('too few items')
  445. >>> one(it, too_short=too_short) # doctest: +IGNORE_EXCEPTION_DETAIL
  446. Traceback (most recent call last):
  447. ...
  448. IndexError: too few items
  449. Similarly, if *iterable* contains more than one item, ``ValueError`` will
  450. be raised. You may specify a different exception with the *too_long*
  451. keyword:
  452. >>> it = ['too', 'many']
  453. >>> one(it) # doctest: +IGNORE_EXCEPTION_DETAIL
  454. Traceback (most recent call last):
  455. ...
  456. ValueError: Expected exactly one item in iterable, but got 'too',
  457. 'many', and perhaps more.
  458. >>> too_long = RuntimeError
  459. >>> one(it, too_long=too_long) # doctest: +IGNORE_EXCEPTION_DETAIL
  460. Traceback (most recent call last):
  461. ...
  462. RuntimeError
  463. Note that :func:`one` attempts to advance *iterable* twice to ensure there
  464. is only one item. See :func:`spy` or :func:`peekable` to check iterable
  465. contents less destructively.
  466. """
  467. it = iter(iterable)
  468. try:
  469. first_value = next(it)
  470. except StopIteration as exc:
  471. raise (
  472. too_short or ValueError('too few items in iterable (expected 1)')
  473. ) from exc
  474. try:
  475. second_value = next(it)
  476. except StopIteration:
  477. pass
  478. else:
  479. msg = (
  480. 'Expected exactly one item in iterable, but got {!r}, {!r}, '
  481. 'and perhaps more.'.format(first_value, second_value)
  482. )
  483. raise too_long or ValueError(msg)
  484. return first_value
  485. def raise_(exception, *args):
  486. raise exception(*args)
  487. def strictly_n(iterable, n, too_short=None, too_long=None):
  488. """Validate that *iterable* has exactly *n* items and return them if
  489. it does. If it has fewer than *n* items, call function *too_short*
  490. with those items. If it has more than *n* items, call function
  491. *too_long* with the first ``n + 1`` items.
  492. >>> iterable = ['a', 'b', 'c', 'd']
  493. >>> n = 4
  494. >>> list(strictly_n(iterable, n))
  495. ['a', 'b', 'c', 'd']
  496. Note that the returned iterable must be consumed in order for the check to
  497. be made.
  498. By default, *too_short* and *too_long* are functions that raise
  499. ``ValueError``.
  500. >>> list(strictly_n('ab', 3)) # doctest: +IGNORE_EXCEPTION_DETAIL
  501. Traceback (most recent call last):
  502. ...
  503. ValueError: too few items in iterable (got 2)
  504. >>> list(strictly_n('abc', 2)) # doctest: +IGNORE_EXCEPTION_DETAIL
  505. Traceback (most recent call last):
  506. ...
  507. ValueError: too many items in iterable (got at least 3)
  508. You can instead supply functions that do something else.
  509. *too_short* will be called with the number of items in *iterable*.
  510. *too_long* will be called with `n + 1`.
  511. >>> def too_short(item_count):
  512. ... raise RuntimeError
  513. >>> it = strictly_n('abcd', 6, too_short=too_short)
  514. >>> list(it) # doctest: +IGNORE_EXCEPTION_DETAIL
  515. Traceback (most recent call last):
  516. ...
  517. RuntimeError
  518. >>> def too_long(item_count):
  519. ... print('The boss is going to hear about this')
  520. >>> it = strictly_n('abcdef', 4, too_long=too_long)
  521. >>> list(it)
  522. The boss is going to hear about this
  523. ['a', 'b', 'c', 'd']
  524. """
  525. if too_short is None:
  526. too_short = lambda item_count: raise_(
  527. ValueError,
  528. 'Too few items in iterable (got {})'.format(item_count),
  529. )
  530. if too_long is None:
  531. too_long = lambda item_count: raise_(
  532. ValueError,
  533. 'Too many items in iterable (got at least {})'.format(item_count),
  534. )
  535. it = iter(iterable)
  536. for i in range(n):
  537. try:
  538. item = next(it)
  539. except StopIteration:
  540. too_short(i)
  541. return
  542. else:
  543. yield item
  544. try:
  545. next(it)
  546. except StopIteration:
  547. pass
  548. else:
  549. too_long(n + 1)
  550. def distinct_permutations(iterable, r=None):
  551. """Yield successive distinct permutations of the elements in *iterable*.
  552. >>> sorted(distinct_permutations([1, 0, 1]))
  553. [(0, 1, 1), (1, 0, 1), (1, 1, 0)]
  554. Equivalent to ``set(permutations(iterable))``, except duplicates are not
  555. generated and thrown away. For larger input sequences this is much more
  556. efficient.
  557. Duplicate permutations arise when there are duplicated elements in the
  558. input iterable. The number of items returned is
  559. `n! / (x_1! * x_2! * ... * x_n!)`, where `n` is the total number of
  560. items input, and each `x_i` is the count of a distinct item in the input
  561. sequence.
  562. If *r* is given, only the *r*-length permutations are yielded.
  563. >>> sorted(distinct_permutations([1, 0, 1], r=2))
  564. [(0, 1), (1, 0), (1, 1)]
  565. >>> sorted(distinct_permutations(range(3), r=2))
  566. [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
  567. """
  568. # Algorithm: https://w.wiki/Qai
  569. def _full(A):
  570. while True:
  571. # Yield the permutation we have
  572. yield tuple(A)
  573. # Find the largest index i such that A[i] < A[i + 1]
  574. for i in range(size - 2, -1, -1):
  575. if A[i] < A[i + 1]:
  576. break
  577. # If no such index exists, this permutation is the last one
  578. else:
  579. return
  580. # Find the largest index j greater than j such that A[i] < A[j]
  581. for j in range(size - 1, i, -1):
  582. if A[i] < A[j]:
  583. break
  584. # Swap the value of A[i] with that of A[j], then reverse the
  585. # sequence from A[i + 1] to form the new permutation
  586. A[i], A[j] = A[j], A[i]
  587. A[i + 1 :] = A[: i - size : -1] # A[i + 1:][::-1]
  588. # Algorithm: modified from the above
  589. def _partial(A, r):
  590. # Split A into the first r items and the last r items
  591. head, tail = A[:r], A[r:]
  592. right_head_indexes = range(r - 1, -1, -1)
  593. left_tail_indexes = range(len(tail))
  594. while True:
  595. # Yield the permutation we have
  596. yield tuple(head)
  597. # Starting from the right, find the first index of the head with
  598. # value smaller than the maximum value of the tail - call it i.
  599. pivot = tail[-1]
  600. for i in right_head_indexes:
  601. if head[i] < pivot:
  602. break
  603. pivot = head[i]
  604. else:
  605. return
  606. # Starting from the left, find the first value of the tail
  607. # with a value greater than head[i] and swap.
  608. for j in left_tail_indexes:
  609. if tail[j] > head[i]:
  610. head[i], tail[j] = tail[j], head[i]
  611. break
  612. # If we didn't find one, start from the right and find the first
  613. # index of the head with a value greater than head[i] and swap.
  614. else:
  615. for j in right_head_indexes:
  616. if head[j] > head[i]:
  617. head[i], head[j] = head[j], head[i]
  618. break
  619. # Reverse head[i + 1:] and swap it with tail[:r - (i + 1)]
  620. tail += head[: i - r : -1] # head[i + 1:][::-1]
  621. i += 1
  622. head[i:], tail[:] = tail[: r - i], tail[r - i :]
  623. items = sorted(iterable)
  624. size = len(items)
  625. if r is None:
  626. r = size
  627. if 0 < r <= size:
  628. return _full(items) if (r == size) else _partial(items, r)
  629. return iter(() if r else ((),))
  630. def intersperse(e, iterable, n=1):
  631. """Intersperse filler element *e* among the items in *iterable*, leaving
  632. *n* items between each filler element.
  633. >>> list(intersperse('!', [1, 2, 3, 4, 5]))
  634. [1, '!', 2, '!', 3, '!', 4, '!', 5]
  635. >>> list(intersperse(None, [1, 2, 3, 4, 5], n=2))
  636. [1, 2, None, 3, 4, None, 5]
  637. """
  638. if n == 0:
  639. raise ValueError('n must be > 0')
  640. elif n == 1:
  641. # interleave(repeat(e), iterable) -> e, x_0, e, x_1, e, x_2...
  642. # islice(..., 1, None) -> x_0, e, x_1, e, x_2...
  643. return islice(interleave(repeat(e), iterable), 1, None)
  644. else:
  645. # interleave(filler, chunks) -> [e], [x_0, x_1], [e], [x_2, x_3]...
  646. # islice(..., 1, None) -> [x_0, x_1], [e], [x_2, x_3]...
  647. # flatten(...) -> x_0, x_1, e, x_2, x_3...
  648. filler = repeat([e])
  649. chunks = chunked(iterable, n)
  650. return flatten(islice(interleave(filler, chunks), 1, None))
  651. def unique_to_each(*iterables):
  652. """Return the elements from each of the input iterables that aren't in the
  653. other input iterables.
  654. For example, suppose you have a set of packages, each with a set of
  655. dependencies::
  656. {'pkg_1': {'A', 'B'}, 'pkg_2': {'B', 'C'}, 'pkg_3': {'B', 'D'}}
  657. If you remove one package, which dependencies can also be removed?
  658. If ``pkg_1`` is removed, then ``A`` is no longer necessary - it is not
  659. associated with ``pkg_2`` or ``pkg_3``. Similarly, ``C`` is only needed for
  660. ``pkg_2``, and ``D`` is only needed for ``pkg_3``::
  661. >>> unique_to_each({'A', 'B'}, {'B', 'C'}, {'B', 'D'})
  662. [['A'], ['C'], ['D']]
  663. If there are duplicates in one input iterable that aren't in the others
  664. they will be duplicated in the output. Input order is preserved::
  665. >>> unique_to_each("mississippi", "missouri")
  666. [['p', 'p'], ['o', 'u', 'r']]
  667. It is assumed that the elements of each iterable are hashable.
  668. """
  669. pool = [list(it) for it in iterables]
  670. counts = Counter(chain.from_iterable(map(set, pool)))
  671. uniques = {element for element in counts if counts[element] == 1}
  672. return [list(filter(uniques.__contains__, it)) for it in pool]
  673. def windowed(seq, n, fillvalue=None, step=1):
  674. """Return a sliding window of width *n* over the given iterable.
  675. >>> all_windows = windowed([1, 2, 3, 4, 5], 3)
  676. >>> list(all_windows)
  677. [(1, 2, 3), (2, 3, 4), (3, 4, 5)]
  678. When the window is larger than the iterable, *fillvalue* is used in place
  679. of missing values:
  680. >>> list(windowed([1, 2, 3], 4))
  681. [(1, 2, 3, None)]
  682. Each window will advance in increments of *step*:
  683. >>> list(windowed([1, 2, 3, 4, 5, 6], 3, fillvalue='!', step=2))
  684. [(1, 2, 3), (3, 4, 5), (5, 6, '!')]
  685. To slide into the iterable's items, use :func:`chain` to add filler items
  686. to the left:
  687. >>> iterable = [1, 2, 3, 4]
  688. >>> n = 3
  689. >>> padding = [None] * (n - 1)
  690. >>> list(windowed(chain(padding, iterable), 3))
  691. [(None, None, 1), (None, 1, 2), (1, 2, 3), (2, 3, 4)]
  692. """
  693. if n < 0:
  694. raise ValueError('n must be >= 0')
  695. if n == 0:
  696. yield ()
  697. return
  698. if step < 1:
  699. raise ValueError('step must be >= 1')
  700. iterable = iter(seq)
  701. # Generate first window
  702. window = deque(islice(iterable, n), maxlen=n)
  703. # Deal with the first window not being full
  704. if not window:
  705. return
  706. if len(window) < n:
  707. yield tuple(window) + ((fillvalue,) * (n - len(window)))
  708. return
  709. yield tuple(window)
  710. # Create the filler for the next windows. The padding ensures
  711. # we have just enough elements to fill the last window.
  712. padding = (fillvalue,) * (n - 1 if step >= n else step - 1)
  713. filler = map(window.append, chain(iterable, padding))
  714. # Generate the rest of the windows
  715. for _ in islice(filler, step - 1, None, step):
  716. yield tuple(window)
  717. def substrings(iterable):
  718. """Yield all of the substrings of *iterable*.
  719. >>> [''.join(s) for s in substrings('more')]
  720. ['m', 'o', 'r', 'e', 'mo', 'or', 're', 'mor', 'ore', 'more']
  721. Note that non-string iterables can also be subdivided.
  722. >>> list(substrings([0, 1, 2]))
  723. [(0,), (1,), (2,), (0, 1), (1, 2), (0, 1, 2)]
  724. """
  725. # The length-1 substrings
  726. seq = []
  727. for item in iter(iterable):
  728. seq.append(item)
  729. yield (item,)
  730. seq = tuple(seq)
  731. item_count = len(seq)
  732. # And the rest
  733. for n in range(2, item_count + 1):
  734. for i in range(item_count - n + 1):
  735. yield seq[i : i + n]
  736. def substrings_indexes(seq, reverse=False):
  737. """Yield all substrings and their positions in *seq*
  738. The items yielded will be a tuple of the form ``(substr, i, j)``, where
  739. ``substr == seq[i:j]``.
  740. This function only works for iterables that support slicing, such as
  741. ``str`` objects.
  742. >>> for item in substrings_indexes('more'):
  743. ... print(item)
  744. ('m', 0, 1)
  745. ('o', 1, 2)
  746. ('r', 2, 3)
  747. ('e', 3, 4)
  748. ('mo', 0, 2)
  749. ('or', 1, 3)
  750. ('re', 2, 4)
  751. ('mor', 0, 3)
  752. ('ore', 1, 4)
  753. ('more', 0, 4)
  754. Set *reverse* to ``True`` to yield the same items in the opposite order.
  755. """
  756. r = range(1, len(seq) + 1)
  757. if reverse:
  758. r = reversed(r)
  759. return (
  760. (seq[i : i + L], i, i + L) for L in r for i in range(len(seq) - L + 1)
  761. )
  762. class bucket:
  763. """Wrap *iterable* and return an object that buckets the iterable into
  764. child iterables based on a *key* function.
  765. >>> iterable = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'b3']
  766. >>> s = bucket(iterable, key=lambda x: x[0]) # Bucket by 1st character
  767. >>> sorted(list(s)) # Get the keys
  768. ['a', 'b', 'c']
  769. >>> a_iterable = s['a']
  770. >>> next(a_iterable)
  771. 'a1'
  772. >>> next(a_iterable)
  773. 'a2'
  774. >>> list(s['b'])
  775. ['b1', 'b2', 'b3']
  776. The original iterable will be advanced and its items will be cached until
  777. they are used by the child iterables. This may require significant storage.
  778. By default, attempting to select a bucket to which no items belong will
  779. exhaust the iterable and cache all values.
  780. If you specify a *validator* function, selected buckets will instead be
  781. checked against it.
  782. >>> from itertools import count
  783. >>> it = count(1, 2) # Infinite sequence of odd numbers
  784. >>> key = lambda x: x % 10 # Bucket by last digit
  785. >>> validator = lambda x: x in {1, 3, 5, 7, 9} # Odd digits only
  786. >>> s = bucket(it, key=key, validator=validator)
  787. >>> 2 in s
  788. False
  789. >>> list(s[2])
  790. []
  791. """
  792. def __init__(self, iterable, key, validator=None):
  793. self._it = iter(iterable)
  794. self._key = key
  795. self._cache = defaultdict(deque)
  796. self._validator = validator or (lambda x: True)
  797. def __contains__(self, value):
  798. if not self._validator(value):
  799. return False
  800. try:
  801. item = next(self[value])
  802. except StopIteration:
  803. return False
  804. else:
  805. self._cache[value].appendleft(item)
  806. return True
  807. def _get_values(self, value):
  808. """
  809. Helper to yield items from the parent iterator that match *value*.
  810. Items that don't match are stored in the local cache as they
  811. are encountered.
  812. """
  813. while True:
  814. # If we've cached some items that match the target value, emit
  815. # the first one and evict it from the cache.
  816. if self._cache[value]:
  817. yield self._cache[value].popleft()
  818. # Otherwise we need to advance the parent iterator to search for
  819. # a matching item, caching the rest.
  820. else:
  821. while True:
  822. try:
  823. item = next(self._it)
  824. except StopIteration:
  825. return
  826. item_value = self._key(item)
  827. if item_value == value:
  828. yield item
  829. break
  830. elif self._validator(item_value):
  831. self._cache[item_value].append(item)
  832. def __iter__(self):
  833. for item in self._it:
  834. item_value = self._key(item)
  835. if self._validator(item_value):
  836. self._cache[item_value].append(item)
  837. yield from self._cache.keys()
  838. def __getitem__(self, value):
  839. if not self._validator(value):
  840. return iter(())
  841. return self._get_values(value)
  842. def spy(iterable, n=1):
  843. """Return a 2-tuple with a list containing the first *n* elements of
  844. *iterable*, and an iterator with the same items as *iterable*.
  845. This allows you to "look ahead" at the items in the iterable without
  846. advancing it.
  847. There is one item in the list by default:
  848. >>> iterable = 'abcdefg'
  849. >>> head, iterable = spy(iterable)
  850. >>> head
  851. ['a']
  852. >>> list(iterable)
  853. ['a', 'b', 'c', 'd', 'e', 'f', 'g']
  854. You may use unpacking to retrieve items instead of lists:
  855. >>> (head,), iterable = spy('abcdefg')
  856. >>> head
  857. 'a'
  858. >>> (first, second), iterable = spy('abcdefg', 2)
  859. >>> first
  860. 'a'
  861. >>> second
  862. 'b'
  863. The number of items requested can be larger than the number of items in
  864. the iterable:
  865. >>> iterable = [1, 2, 3, 4, 5]
  866. >>> head, iterable = spy(iterable, 10)
  867. >>> head
  868. [1, 2, 3, 4, 5]
  869. >>> list(iterable)
  870. [1, 2, 3, 4, 5]
  871. """
  872. it = iter(iterable)
  873. head = take(n, it)
  874. return head.copy(), chain(head, it)
  875. def interleave(*iterables):
  876. """Return a new iterable yielding from each iterable in turn,
  877. until the shortest is exhausted.
  878. >>> list(interleave([1, 2, 3], [4, 5], [6, 7, 8]))
  879. [1, 4, 6, 2, 5, 7]
  880. For a version that doesn't terminate after the shortest iterable is
  881. exhausted, see :func:`interleave_longest`.
  882. """
  883. return chain.from_iterable(zip(*iterables))
  884. def interleave_longest(*iterables):
  885. """Return a new iterable yielding from each iterable in turn,
  886. skipping any that are exhausted.
  887. >>> list(interleave_longest([1, 2, 3], [4, 5], [6, 7, 8]))
  888. [1, 4, 6, 2, 5, 7, 3, 8]
  889. This function produces the same output as :func:`roundrobin`, but may
  890. perform better for some inputs (in particular when the number of iterables
  891. is large).
  892. """
  893. i = chain.from_iterable(zip_longest(*iterables, fillvalue=_marker))
  894. return (x for x in i if x is not _marker)
  895. def interleave_evenly(iterables, lengths=None):
  896. """
  897. Interleave multiple iterables so that their elements are evenly distributed
  898. throughout the output sequence.
  899. >>> iterables = [1, 2, 3, 4, 5], ['a', 'b']
  900. >>> list(interleave_evenly(iterables))
  901. [1, 2, 'a', 3, 4, 'b', 5]
  902. >>> iterables = [[1, 2, 3], [4, 5], [6, 7, 8]]
  903. >>> list(interleave_evenly(iterables))
  904. [1, 6, 4, 2, 7, 3, 8, 5]
  905. This function requires iterables of known length. Iterables without
  906. ``__len__()`` can be used by manually specifying lengths with *lengths*:
  907. >>> from itertools import combinations, repeat
  908. >>> iterables = [combinations(range(4), 2), ['a', 'b', 'c']]
  909. >>> lengths = [4 * (4 - 1) // 2, 3]
  910. >>> list(interleave_evenly(iterables, lengths=lengths))
  911. [(0, 1), (0, 2), 'a', (0, 3), (1, 2), 'b', (1, 3), (2, 3), 'c']
  912. Based on Bresenham's algorithm.
  913. """
  914. if lengths is None:
  915. try:
  916. lengths = [len(it) for it in iterables]
  917. except TypeError:
  918. raise ValueError(
  919. 'Iterable lengths could not be determined automatically. '
  920. 'Specify them with the lengths keyword.'
  921. )
  922. elif len(iterables) != len(lengths):
  923. raise ValueError('Mismatching number of iterables and lengths.')
  924. dims = len(lengths)
  925. # sort iterables by length, descending
  926. lengths_permute = sorted(
  927. range(dims), key=lambda i: lengths[i], reverse=True
  928. )
  929. lengths_desc = [lengths[i] for i in lengths_permute]
  930. iters_desc = [iter(iterables[i]) for i in lengths_permute]
  931. # the longest iterable is the primary one (Bresenham: the longest
  932. # distance along an axis)
  933. delta_primary, deltas_secondary = lengths_desc[0], lengths_desc[1:]
  934. iter_primary, iters_secondary = iters_desc[0], iters_desc[1:]
  935. errors = [delta_primary // dims] * len(deltas_secondary)
  936. to_yield = sum(lengths)
  937. while to_yield:
  938. yield next(iter_primary)
  939. to_yield -= 1
  940. # update errors for each secondary iterable
  941. errors = [e - delta for e, delta in zip(errors, deltas_secondary)]
  942. # those iterables for which the error is negative are yielded
  943. # ("diagonal step" in Bresenham)
  944. for i, e_ in enumerate(errors):
  945. if e_ < 0:
  946. yield next(iters_secondary[i])
  947. to_yield -= 1
  948. errors[i] += delta_primary
  949. def collapse(iterable, base_type=None, levels=None):
  950. """Flatten an iterable with multiple levels of nesting (e.g., a list of
  951. lists of tuples) into non-iterable types.
  952. >>> iterable = [(1, 2), ([3, 4], [[5], [6]])]
  953. >>> list(collapse(iterable))
  954. [1, 2, 3, 4, 5, 6]
  955. Binary and text strings are not considered iterable and
  956. will not be collapsed.
  957. To avoid collapsing other types, specify *base_type*:
  958. >>> iterable = ['ab', ('cd', 'ef'), ['gh', 'ij']]
  959. >>> list(collapse(iterable, base_type=tuple))
  960. ['ab', ('cd', 'ef'), 'gh', 'ij']
  961. Specify *levels* to stop flattening after a certain level:
  962. >>> iterable = [('a', ['b']), ('c', ['d'])]
  963. >>> list(collapse(iterable)) # Fully flattened
  964. ['a', 'b', 'c', 'd']
  965. >>> list(collapse(iterable, levels=1)) # Only one level flattened
  966. ['a', ['b'], 'c', ['d']]
  967. """
  968. stack = deque()
  969. # Add our first node group, treat the iterable as a single node
  970. stack.appendleft((0, repeat(iterable, 1)))
  971. while stack:
  972. node_group = stack.popleft()
  973. level, nodes = node_group
  974. # Check if beyond max level
  975. if levels is not None and level > levels:
  976. yield from nodes
  977. continue
  978. for node in nodes:
  979. # Check if done iterating
  980. if isinstance(node, (str, bytes)) or (
  981. (base_type is not None) and isinstance(node, base_type)
  982. ):
  983. yield node
  984. # Otherwise try to create child nodes
  985. else:
  986. try:
  987. tree = iter(node)
  988. except TypeError:
  989. yield node
  990. else:
  991. # Save our current location
  992. stack.appendleft(node_group)
  993. # Append the new child node
  994. stack.appendleft((level + 1, tree))
  995. # Break to process child node
  996. break
  997. def side_effect(func, iterable, chunk_size=None, before=None, after=None):
  998. """Invoke *func* on each item in *iterable* (or on each *chunk_size* group
  999. of items) before yielding the item.
  1000. `func` must be a function that takes a single argument. Its return value
  1001. will be discarded.
  1002. *before* and *after* are optional functions that take no arguments. They
  1003. will be executed before iteration starts and after it ends, respectively.
  1004. `side_effect` can be used for logging, updating progress bars, or anything
  1005. that is not functionally "pure."
  1006. Emitting a status message:
  1007. >>> from more_itertools import consume
  1008. >>> func = lambda item: print('Received {}'.format(item))
  1009. >>> consume(side_effect(func, range(2)))
  1010. Received 0
  1011. Received 1
  1012. Operating on chunks of items:
  1013. >>> pair_sums = []
  1014. >>> func = lambda chunk: pair_sums.append(sum(chunk))
  1015. >>> list(side_effect(func, [0, 1, 2, 3, 4, 5], 2))
  1016. [0, 1, 2, 3, 4, 5]
  1017. >>> list(pair_sums)
  1018. [1, 5, 9]
  1019. Writing to a file-like object:
  1020. >>> from io import StringIO
  1021. >>> from more_itertools import consume
  1022. >>> f = StringIO()
  1023. >>> func = lambda x: print(x, file=f)
  1024. >>> before = lambda: print(u'HEADER', file=f)
  1025. >>> after = f.close
  1026. >>> it = [u'a', u'b', u'c']
  1027. >>> consume(side_effect(func, it, before=before, after=after))
  1028. >>> f.closed
  1029. True
  1030. """
  1031. try:
  1032. if before is not None:
  1033. before()
  1034. if chunk_size is None:
  1035. for item in iterable:
  1036. func(item)
  1037. yield item
  1038. else:
  1039. for chunk in chunked(iterable, chunk_size):
  1040. func(chunk)
  1041. yield from chunk
  1042. finally:
  1043. if after is not None:
  1044. after()
  1045. def sliced(seq, n, strict=False):
  1046. """Yield slices of length *n* from the sequence *seq*.
  1047. >>> list(sliced((1, 2, 3, 4, 5, 6), 3))
  1048. [(1, 2, 3), (4, 5, 6)]
  1049. By the default, the last yielded slice will have fewer than *n* elements
  1050. if the length of *seq* is not divisible by *n*:
  1051. >>> list(sliced((1, 2, 3, 4, 5, 6, 7, 8), 3))
  1052. [(1, 2, 3), (4, 5, 6), (7, 8)]
  1053. If the length of *seq* is not divisible by *n* and *strict* is
  1054. ``True``, then ``ValueError`` will be raised before the last
  1055. slice is yielded.
  1056. This function will only work for iterables that support slicing.
  1057. For non-sliceable iterables, see :func:`chunked`.
  1058. """
  1059. iterator = takewhile(len, (seq[i : i + n] for i in count(0, n)))
  1060. if strict:
  1061. def ret():
  1062. for _slice in iterator:
  1063. if len(_slice) != n:
  1064. raise ValueError("seq is not divisible by n.")
  1065. yield _slice
  1066. return iter(ret())
  1067. else:
  1068. return iterator
  1069. def split_at(iterable, pred, maxsplit=-1, keep_separator=False):
  1070. """Yield lists of items from *iterable*, where each list is delimited by
  1071. an item where callable *pred* returns ``True``.
  1072. >>> list(split_at('abcdcba', lambda x: x == 'b'))
  1073. [['a'], ['c', 'd', 'c'], ['a']]
  1074. >>> list(split_at(range(10), lambda n: n % 2 == 1))
  1075. [[0], [2], [4], [6], [8], []]
  1076. At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,
  1077. then there is no limit on the number of splits:
  1078. >>> list(split_at(range(10), lambda n: n % 2 == 1, maxsplit=2))
  1079. [[0], [2], [4, 5, 6, 7, 8, 9]]
  1080. By default, the delimiting items are not included in the output.
  1081. To include them, set *keep_separator* to ``True``.
  1082. >>> list(split_at('abcdcba', lambda x: x == 'b', keep_separator=True))
  1083. [['a'], ['b'], ['c', 'd', 'c'], ['b'], ['a']]
  1084. """
  1085. if maxsplit == 0:
  1086. yield list(iterable)
  1087. return
  1088. buf = []
  1089. it = iter(iterable)
  1090. for item in it:
  1091. if pred(item):
  1092. yield buf
  1093. if keep_separator:
  1094. yield [item]
  1095. if maxsplit == 1:
  1096. yield list(it)
  1097. return
  1098. buf = []
  1099. maxsplit -= 1
  1100. else:
  1101. buf.append(item)
  1102. yield buf
  1103. def split_before(iterable, pred, maxsplit=-1):
  1104. """Yield lists of items from *iterable*, where each list ends just before
  1105. an item for which callable *pred* returns ``True``:
  1106. >>> list(split_before('OneTwo', lambda s: s.isupper()))
  1107. [['O', 'n', 'e'], ['T', 'w', 'o']]
  1108. >>> list(split_before(range(10), lambda n: n % 3 == 0))
  1109. [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
  1110. At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,
  1111. then there is no limit on the number of splits:
  1112. >>> list(split_before(range(10), lambda n: n % 3 == 0, maxsplit=2))
  1113. [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]
  1114. """
  1115. if maxsplit == 0:
  1116. yield list(iterable)
  1117. return
  1118. buf = []
  1119. it = iter(iterable)
  1120. for item in it:
  1121. if pred(item) and buf:
  1122. yield buf
  1123. if maxsplit == 1:
  1124. yield [item] + list(it)
  1125. return
  1126. buf = []
  1127. maxsplit -= 1
  1128. buf.append(item)
  1129. if buf:
  1130. yield buf
  1131. def split_after(iterable, pred, maxsplit=-1):
  1132. """Yield lists of items from *iterable*, where each list ends with an
  1133. item where callable *pred* returns ``True``:
  1134. >>> list(split_after('one1two2', lambda s: s.isdigit()))
  1135. [['o', 'n', 'e', '1'], ['t', 'w', 'o', '2']]
  1136. >>> list(split_after(range(10), lambda n: n % 3 == 0))
  1137. [[0], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
  1138. At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,
  1139. then there is no limit on the number of splits:
  1140. >>> list(split_after(range(10), lambda n: n % 3 == 0, maxsplit=2))
  1141. [[0], [1, 2, 3], [4, 5, 6, 7, 8, 9]]
  1142. """
  1143. if maxsplit == 0:
  1144. yield list(iterable)
  1145. return
  1146. buf = []
  1147. it = iter(iterable)
  1148. for item in it:
  1149. buf.append(item)
  1150. if pred(item) and buf:
  1151. yield buf
  1152. if maxsplit == 1:
  1153. buf = list(it)
  1154. if buf:
  1155. yield buf
  1156. return
  1157. buf = []
  1158. maxsplit -= 1
  1159. if buf:
  1160. yield buf
  1161. def split_when(iterable, pred, maxsplit=-1):
  1162. """Split *iterable* into pieces based on the output of *pred*.
  1163. *pred* should be a function that takes successive pairs of items and
  1164. returns ``True`` if the iterable should be split in between them.
  1165. For example, to find runs of increasing numbers, split the iterable when
  1166. element ``i`` is larger than element ``i + 1``:
  1167. >>> list(split_when([1, 2, 3, 3, 2, 5, 2, 4, 2], lambda x, y: x > y))
  1168. [[1, 2, 3, 3], [2, 5], [2, 4], [2]]
  1169. At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,
  1170. then there is no limit on the number of splits:
  1171. >>> list(split_when([1, 2, 3, 3, 2, 5, 2, 4, 2],
  1172. ... lambda x, y: x > y, maxsplit=2))
  1173. [[1, 2, 3, 3], [2, 5], [2, 4, 2]]
  1174. """
  1175. if maxsplit == 0:
  1176. yield list(iterable)
  1177. return
  1178. it = iter(iterable)
  1179. try:
  1180. cur_item = next(it)
  1181. except StopIteration:
  1182. return
  1183. buf = [cur_item]
  1184. for next_item in it:
  1185. if pred(cur_item, next_item):
  1186. yield buf
  1187. if maxsplit == 1:
  1188. yield [next_item] + list(it)
  1189. return
  1190. buf = []
  1191. maxsplit -= 1
  1192. buf.append(next_item)
  1193. cur_item = next_item
  1194. yield buf
  1195. def split_into(iterable, sizes):
  1196. """Yield a list of sequential items from *iterable* of length 'n' for each
  1197. integer 'n' in *sizes*.
  1198. >>> list(split_into([1,2,3,4,5,6], [1,2,3]))
  1199. [[1], [2, 3], [4, 5, 6]]
  1200. If the sum of *sizes* is smaller than the length of *iterable*, then the
  1201. remaining items of *iterable* will not be returned.
  1202. >>> list(split_into([1,2,3,4,5,6], [2,3]))
  1203. [[1, 2], [3, 4, 5]]
  1204. If the sum of *sizes* is larger than the length of *iterable*, fewer items
  1205. will be returned in the iteration that overruns *iterable* and further
  1206. lists will be empty:
  1207. >>> list(split_into([1,2,3,4], [1,2,3,4]))
  1208. [[1], [2, 3], [4], []]
  1209. When a ``None`` object is encountered in *sizes*, the returned list will
  1210. contain items up to the end of *iterable* the same way that itertools.slice
  1211. does:
  1212. >>> list(split_into([1,2,3,4,5,6,7,8,9,0], [2,3,None]))
  1213. [[1, 2], [3, 4, 5], [6, 7, 8, 9, 0]]
  1214. :func:`split_into` can be useful for grouping a series of items where the
  1215. sizes of the groups are not uniform. An example would be where in a row
  1216. from a table, multiple columns represent elements of the same feature
  1217. (e.g. a point represented by x,y,z) but, the format is not the same for
  1218. all columns.
  1219. """
  1220. # convert the iterable argument into an iterator so its contents can
  1221. # be consumed by islice in case it is a generator
  1222. it = iter(iterable)
  1223. for size in sizes:
  1224. if size is None:
  1225. yield list(it)
  1226. return
  1227. else:
  1228. yield list(islice(it, size))
  1229. def padded(iterable, fillvalue=None, n=None, next_multiple=False):
  1230. """Yield the elements from *iterable*, followed by *fillvalue*, such that
  1231. at least *n* items are emitted.
  1232. >>> list(padded([1, 2, 3], '?', 5))
  1233. [1, 2, 3, '?', '?']
  1234. If *next_multiple* is ``True``, *fillvalue* will be emitted until the
  1235. number of items emitted is a multiple of *n*:
  1236. >>> list(padded([1, 2, 3, 4], n=3, next_multiple=True))
  1237. [1, 2, 3, 4, None, None]
  1238. If *n* is ``None``, *fillvalue* will be emitted indefinitely.
  1239. To create an *iterable* of exactly size *n*, you can truncate with
  1240. :func:`islice`.
  1241. >>> list(islice(padded([1, 2, 3], '?'), 5))
  1242. [1, 2, 3, '?', '?']
  1243. >>> list(islice(padded([1, 2, 3, 4, 5, 6, 7, 8], '?'), 5))
  1244. [1, 2, 3, 4, 5]
  1245. """
  1246. iterable = iter(iterable)
  1247. iterable_with_repeat = chain(iterable, repeat(fillvalue))
  1248. if n is None:
  1249. return iterable_with_repeat
  1250. elif n < 1:
  1251. raise ValueError('n must be at least 1')
  1252. elif next_multiple:
  1253. def slice_generator():
  1254. for first in iterable:
  1255. yield (first,)
  1256. yield islice(iterable_with_repeat, n - 1)
  1257. # While elements exist produce slices of size n
  1258. return chain.from_iterable(slice_generator())
  1259. else:
  1260. # Ensure the first batch is at least size n then iterate
  1261. return chain(islice(iterable_with_repeat, n), iterable)
  1262. def repeat_each(iterable, n=2):
  1263. """Repeat each element in *iterable* *n* times.
  1264. >>> list(repeat_each('ABC', 3))
  1265. ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']
  1266. """
  1267. return chain.from_iterable(map(repeat, iterable, repeat(n)))
  1268. def repeat_last(iterable, default=None):
  1269. """After the *iterable* is exhausted, keep yielding its last element.
  1270. >>> list(islice(repeat_last(range(3)), 5))
  1271. [0, 1, 2, 2, 2]
  1272. If the iterable is empty, yield *default* forever::
  1273. >>> list(islice(repeat_last(range(0), 42), 5))
  1274. [42, 42, 42, 42, 42]
  1275. """
  1276. item = _marker
  1277. for item in iterable:
  1278. yield item
  1279. final = default if item is _marker else item
  1280. yield from repeat(final)
  1281. def distribute(n, iterable):
  1282. """Distribute the items from *iterable* among *n* smaller iterables.
  1283. >>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6])
  1284. >>> list(group_1)
  1285. [1, 3, 5]
  1286. >>> list(group_2)
  1287. [2, 4, 6]
  1288. If the length of *iterable* is not evenly divisible by *n*, then the
  1289. length of the returned iterables will not be identical:
  1290. >>> children = distribute(3, [1, 2, 3, 4, 5, 6, 7])
  1291. >>> [list(c) for c in children]
  1292. [[1, 4, 7], [2, 5], [3, 6]]
  1293. If the length of *iterable* is smaller than *n*, then the last returned
  1294. iterables will be empty:
  1295. >>> children = distribute(5, [1, 2, 3])
  1296. >>> [list(c) for c in children]
  1297. [[1], [2], [3], [], []]
  1298. This function uses :func:`itertools.tee` and may require significant
  1299. storage.
  1300. If you need the order items in the smaller iterables to match the
  1301. original iterable, see :func:`divide`.
  1302. """
  1303. if n < 1:
  1304. raise ValueError('n must be at least 1')
  1305. children = tee(iterable, n)
  1306. return [islice(it, index, None, n) for index, it in enumerate(children)]
  1307. def stagger(iterable, offsets=(-1, 0, 1), longest=False, fillvalue=None):
  1308. """Yield tuples whose elements are offset from *iterable*.
  1309. The amount by which the `i`-th item in each tuple is offset is given by
  1310. the `i`-th item in *offsets*.
  1311. >>> list(stagger([0, 1, 2, 3]))
  1312. [(None, 0, 1), (0, 1, 2), (1, 2, 3)]
  1313. >>> list(stagger(range(8), offsets=(0, 2, 4)))
  1314. [(0, 2, 4), (1, 3, 5), (2, 4, 6), (3, 5, 7)]
  1315. By default, the sequence will end when the final element of a tuple is the
  1316. last item in the iterable. To continue until the first element of a tuple
  1317. is the last item in the iterable, set *longest* to ``True``::
  1318. >>> list(stagger([0, 1, 2, 3], longest=True))
  1319. [(None, 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, None), (3, None, None)]
  1320. By default, ``None`` will be used to replace offsets beyond the end of the
  1321. sequence. Specify *fillvalue* to use some other value.
  1322. """
  1323. children = tee(iterable, len(offsets))
  1324. return zip_offset(
  1325. *children, offsets=offsets, longest=longest, fillvalue=fillvalue
  1326. )
  1327. def zip_equal(*iterables):
  1328. """``zip`` the input *iterables* together, but raise
  1329. ``UnequalIterablesError`` if they aren't all the same length.
  1330. >>> it_1 = range(3)
  1331. >>> it_2 = iter('abc')
  1332. >>> list(zip_equal(it_1, it_2))
  1333. [(0, 'a'), (1, 'b'), (2, 'c')]
  1334. >>> it_1 = range(3)
  1335. >>> it_2 = iter('abcd')
  1336. >>> list(zip_equal(it_1, it_2)) # doctest: +IGNORE_EXCEPTION_DETAIL
  1337. Traceback (most recent call last):
  1338. ...
  1339. more_itertools.more.UnequalIterablesError: Iterables have different
  1340. lengths
  1341. """
  1342. if hexversion >= 0x30A00A6:
  1343. warnings.warn(
  1344. (
  1345. 'zip_equal will be removed in a future version of '
  1346. 'more-itertools. Use the builtin zip function with '
  1347. 'strict=True instead.'
  1348. ),
  1349. DeprecationWarning,
  1350. )
  1351. return _zip_equal(*iterables)
  1352. def zip_offset(*iterables, offsets, longest=False, fillvalue=None):
  1353. """``zip`` the input *iterables* together, but offset the `i`-th iterable
  1354. by the `i`-th item in *offsets*.
  1355. >>> list(zip_offset('0123', 'abcdef', offsets=(0, 1)))
  1356. [('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e')]
  1357. This can be used as a lightweight alternative to SciPy or pandas to analyze
  1358. data sets in which some series have a lead or lag relationship.
  1359. By default, the sequence will end when the shortest iterable is exhausted.
  1360. To continue until the longest iterable is exhausted, set *longest* to
  1361. ``True``.
  1362. >>> list(zip_offset('0123', 'abcdef', offsets=(0, 1), longest=True))
  1363. [('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e'), (None, 'f')]
  1364. By default, ``None`` will be used to replace offsets beyond the end of the
  1365. sequence. Specify *fillvalue* to use some other value.
  1366. """
  1367. if len(iterables) != len(offsets):
  1368. raise ValueError("Number of iterables and offsets didn't match")
  1369. staggered = []
  1370. for it, n in zip(iterables, offsets):
  1371. if n < 0:
  1372. staggered.append(chain(repeat(fillvalue, -n), it))
  1373. elif n > 0:
  1374. staggered.append(islice(it, n, None))
  1375. else:
  1376. staggered.append(it)
  1377. if longest:
  1378. return zip_longest(*staggered, fillvalue=fillvalue)
  1379. return zip(*staggered)
  1380. def sort_together(iterables, key_list=(0,), key=None, reverse=False):
  1381. """Return the input iterables sorted together, with *key_list* as the
  1382. priority for sorting. All iterables are trimmed to the length of the
  1383. shortest one.
  1384. This can be used like the sorting function in a spreadsheet. If each
  1385. iterable represents a column of data, the key list determines which
  1386. columns are used for sorting.
  1387. By default, all iterables are sorted using the ``0``-th iterable::
  1388. >>> iterables = [(4, 3, 2, 1), ('a', 'b', 'c', 'd')]
  1389. >>> sort_together(iterables)
  1390. [(1, 2, 3, 4), ('d', 'c', 'b', 'a')]
  1391. Set a different key list to sort according to another iterable.
  1392. Specifying multiple keys dictates how ties are broken::
  1393. >>> iterables = [(3, 1, 2), (0, 1, 0), ('c', 'b', 'a')]
  1394. >>> sort_together(iterables, key_list=(1, 2))
  1395. [(2, 3, 1), (0, 0, 1), ('a', 'c', 'b')]
  1396. To sort by a function of the elements of the iterable, pass a *key*
  1397. function. Its arguments are the elements of the iterables corresponding to
  1398. the key list::
  1399. >>> names = ('a', 'b', 'c')
  1400. >>> lengths = (1, 2, 3)
  1401. >>> widths = (5, 2, 1)
  1402. >>> def area(length, width):
  1403. ... return length * width
  1404. >>> sort_together([names, lengths, widths], key_list=(1, 2), key=area)
  1405. [('c', 'b', 'a'), (3, 2, 1), (1, 2, 5)]
  1406. Set *reverse* to ``True`` to sort in descending order.
  1407. >>> sort_together([(1, 2, 3), ('c', 'b', 'a')], reverse=True)
  1408. [(3, 2, 1), ('a', 'b', 'c')]
  1409. """
  1410. if key is None:
  1411. # if there is no key function, the key argument to sorted is an
  1412. # itemgetter
  1413. key_argument = itemgetter(*key_list)
  1414. else:
  1415. # if there is a key function, call it with the items at the offsets
  1416. # specified by the key function as arguments
  1417. key_list = list(key_list)
  1418. if len(key_list) == 1:
  1419. # if key_list contains a single item, pass the item at that offset
  1420. # as the only argument to the key function
  1421. key_offset = key_list[0]
  1422. key_argument = lambda zipped_items: key(zipped_items[key_offset])
  1423. else:
  1424. # if key_list contains multiple items, use itemgetter to return a
  1425. # tuple of items, which we pass as *args to the key function
  1426. get_key_items = itemgetter(*key_list)
  1427. key_argument = lambda zipped_items: key(
  1428. *get_key_items(zipped_items)
  1429. )
  1430. return list(
  1431. zip(*sorted(zip(*iterables), key=key_argument, reverse=reverse))
  1432. )
  1433. def unzip(iterable):
  1434. """The inverse of :func:`zip`, this function disaggregates the elements
  1435. of the zipped *iterable*.
  1436. The ``i``-th iterable contains the ``i``-th element from each element
  1437. of the zipped iterable. The first element is used to determine the
  1438. length of the remaining elements.
  1439. >>> iterable = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
  1440. >>> letters, numbers = unzip(iterable)
  1441. >>> list(letters)
  1442. ['a', 'b', 'c', 'd']
  1443. >>> list(numbers)
  1444. [1, 2, 3, 4]
  1445. This is similar to using ``zip(*iterable)``, but it avoids reading
  1446. *iterable* into memory. Note, however, that this function uses
  1447. :func:`itertools.tee` and thus may require significant storage.
  1448. """
  1449. head, iterable = spy(iter(iterable))
  1450. if not head:
  1451. # empty iterable, e.g. zip([], [], [])
  1452. return ()
  1453. # spy returns a one-length iterable as head
  1454. head = head[0]
  1455. iterables = tee(iterable, len(head))
  1456. def itemgetter(i):
  1457. def getter(obj):
  1458. try:
  1459. return obj[i]
  1460. except IndexError:
  1461. # basically if we have an iterable like
  1462. # iter([(1, 2, 3), (4, 5), (6,)])
  1463. # the second unzipped iterable would fail at the third tuple
  1464. # since it would try to access tup[1]
  1465. # same with the third unzipped iterable and the second tuple
  1466. # to support these "improperly zipped" iterables,
  1467. # we create a custom itemgetter
  1468. # which just stops the unzipped iterables
  1469. # at first length mismatch
  1470. raise StopIteration
  1471. return getter
  1472. return tuple(map(itemgetter(i), it) for i, it in enumerate(iterables))
  1473. def divide(n, iterable):
  1474. """Divide the elements from *iterable* into *n* parts, maintaining
  1475. order.
  1476. >>> group_1, group_2 = divide(2, [1, 2, 3, 4, 5, 6])
  1477. >>> list(group_1)
  1478. [1, 2, 3]
  1479. >>> list(group_2)
  1480. [4, 5, 6]
  1481. If the length of *iterable* is not evenly divisible by *n*, then the
  1482. length of the returned iterables will not be identical:
  1483. >>> children = divide(3, [1, 2, 3, 4, 5, 6, 7])
  1484. >>> [list(c) for c in children]
  1485. [[1, 2, 3], [4, 5], [6, 7]]
  1486. If the length of the iterable is smaller than n, then the last returned
  1487. iterables will be empty:
  1488. >>> children = divide(5, [1, 2, 3])
  1489. >>> [list(c) for c in children]
  1490. [[1], [2], [3], [], []]
  1491. This function will exhaust the iterable before returning.
  1492. If order is not important, see :func:`distribute`, which does not first
  1493. pull the iterable into memory.
  1494. """
  1495. if n < 1:
  1496. raise ValueError('n must be at least 1')
  1497. try:
  1498. iterable[:0]
  1499. except TypeError:
  1500. seq = tuple(iterable)
  1501. else:
  1502. seq = iterable
  1503. q, r = divmod(len(seq), n)
  1504. ret = []
  1505. stop = 0
  1506. for i in range(1, n + 1):
  1507. start = stop
  1508. stop += q + 1 if i <= r else q
  1509. ret.append(iter(seq[start:stop]))
  1510. return ret
  1511. def always_iterable(obj, base_type=(str, bytes)):
  1512. """If *obj* is iterable, return an iterator over its items::
  1513. >>> obj = (1, 2, 3)
  1514. >>> list(always_iterable(obj))
  1515. [1, 2, 3]
  1516. If *obj* is not iterable, return a one-item iterable containing *obj*::
  1517. >>> obj = 1
  1518. >>> list(always_iterable(obj))
  1519. [1]
  1520. If *obj* is ``None``, return an empty iterable:
  1521. >>> obj = None
  1522. >>> list(always_iterable(None))
  1523. []
  1524. By default, binary and text strings are not considered iterable::
  1525. >>> obj = 'foo'
  1526. >>> list(always_iterable(obj))
  1527. ['foo']
  1528. If *base_type* is set, objects for which ``isinstance(obj, base_type)``
  1529. returns ``True`` won't be considered iterable.
  1530. >>> obj = {'a': 1}
  1531. >>> list(always_iterable(obj)) # Iterate over the dict's keys
  1532. ['a']
  1533. >>> list(always_iterable(obj, base_type=dict)) # Treat dicts as a unit
  1534. [{'a': 1}]
  1535. Set *base_type* to ``None`` to avoid any special handling and treat objects
  1536. Python considers iterable as iterable:
  1537. >>> obj = 'foo'
  1538. >>> list(always_iterable(obj, base_type=None))
  1539. ['f', 'o', 'o']
  1540. """
  1541. if obj is None:
  1542. return iter(())
  1543. if (base_type is not None) and isinstance(obj, base_type):
  1544. return iter((obj,))
  1545. try:
  1546. return iter(obj)
  1547. except TypeError:
  1548. return iter((obj,))
  1549. def adjacent(predicate, iterable, distance=1):
  1550. """Return an iterable over `(bool, item)` tuples where the `item` is
  1551. drawn from *iterable* and the `bool` indicates whether
  1552. that item satisfies the *predicate* or is adjacent to an item that does.
  1553. For example, to find whether items are adjacent to a ``3``::
  1554. >>> list(adjacent(lambda x: x == 3, range(6)))
  1555. [(False, 0), (False, 1), (True, 2), (True, 3), (True, 4), (False, 5)]
  1556. Set *distance* to change what counts as adjacent. For example, to find
  1557. whether items are two places away from a ``3``:
  1558. >>> list(adjacent(lambda x: x == 3, range(6), distance=2))
  1559. [(False, 0), (True, 1), (True, 2), (True, 3), (True, 4), (True, 5)]
  1560. This is useful for contextualizing the results of a search function.
  1561. For example, a code comparison tool might want to identify lines that
  1562. have changed, but also surrounding lines to give the viewer of the diff
  1563. context.
  1564. The predicate function will only be called once for each item in the
  1565. iterable.
  1566. See also :func:`groupby_transform`, which can be used with this function
  1567. to group ranges of items with the same `bool` value.
  1568. """
  1569. # Allow distance=0 mainly for testing that it reproduces results with map()
  1570. if distance < 0:
  1571. raise ValueError('distance must be at least 0')
  1572. i1, i2 = tee(iterable)
  1573. padding = [False] * distance
  1574. selected = chain(padding, map(predicate, i1), padding)
  1575. adjacent_to_selected = map(any, windowed(selected, 2 * distance + 1))
  1576. return zip(adjacent_to_selected, i2)
  1577. def groupby_transform(iterable, keyfunc=None, valuefunc=None, reducefunc=None):
  1578. """An extension of :func:`itertools.groupby` that can apply transformations
  1579. to the grouped data.
  1580. * *keyfunc* is a function computing a key value for each item in *iterable*
  1581. * *valuefunc* is a function that transforms the individual items from
  1582. *iterable* after grouping
  1583. * *reducefunc* is a function that transforms each group of items
  1584. >>> iterable = 'aAAbBBcCC'
  1585. >>> keyfunc = lambda k: k.upper()
  1586. >>> valuefunc = lambda v: v.lower()
  1587. >>> reducefunc = lambda g: ''.join(g)
  1588. >>> list(groupby_transform(iterable, keyfunc, valuefunc, reducefunc))
  1589. [('A', 'aaa'), ('B', 'bbb'), ('C', 'ccc')]
  1590. Each optional argument defaults to an identity function if not specified.
  1591. :func:`groupby_transform` is useful when grouping elements of an iterable
  1592. using a separate iterable as the key. To do this, :func:`zip` the iterables
  1593. and pass a *keyfunc* that extracts the first element and a *valuefunc*
  1594. that extracts the second element::
  1595. >>> from operator import itemgetter
  1596. >>> keys = [0, 0, 1, 1, 1, 2, 2, 2, 3]
  1597. >>> values = 'abcdefghi'
  1598. >>> iterable = zip(keys, values)
  1599. >>> grouper = groupby_transform(iterable, itemgetter(0), itemgetter(1))
  1600. >>> [(k, ''.join(g)) for k, g in grouper]
  1601. [(0, 'ab'), (1, 'cde'), (2, 'fgh'), (3, 'i')]
  1602. Note that the order of items in the iterable is significant.
  1603. Only adjacent items are grouped together, so if you don't want any
  1604. duplicate groups, you should sort the iterable by the key function.
  1605. """
  1606. ret = groupby(iterable, keyfunc)
  1607. if valuefunc:
  1608. ret = ((k, map(valuefunc, g)) for k, g in ret)
  1609. if reducefunc:
  1610. ret = ((k, reducefunc(g)) for k, g in ret)
  1611. return ret
  1612. class numeric_range(abc.Sequence, abc.Hashable):
  1613. """An extension of the built-in ``range()`` function whose arguments can
  1614. be any orderable numeric type.
  1615. With only *stop* specified, *start* defaults to ``0`` and *step*
  1616. defaults to ``1``. The output items will match the type of *stop*:
  1617. >>> list(numeric_range(3.5))
  1618. [0.0, 1.0, 2.0, 3.0]
  1619. With only *start* and *stop* specified, *step* defaults to ``1``. The
  1620. output items will match the type of *start*:
  1621. >>> from decimal import Decimal
  1622. >>> start = Decimal('2.1')
  1623. >>> stop = Decimal('5.1')
  1624. >>> list(numeric_range(start, stop))
  1625. [Decimal('2.1'), Decimal('3.1'), Decimal('4.1')]
  1626. With *start*, *stop*, and *step* specified the output items will match
  1627. the type of ``start + step``:
  1628. >>> from fractions import Fraction
  1629. >>> start = Fraction(1, 2) # Start at 1/2
  1630. >>> stop = Fraction(5, 2) # End at 5/2
  1631. >>> step = Fraction(1, 2) # Count by 1/2
  1632. >>> list(numeric_range(start, stop, step))
  1633. [Fraction(1, 2), Fraction(1, 1), Fraction(3, 2), Fraction(2, 1)]
  1634. If *step* is zero, ``ValueError`` is raised. Negative steps are supported:
  1635. >>> list(numeric_range(3, -1, -1.0))
  1636. [3.0, 2.0, 1.0, 0.0]
  1637. Be aware of the limitations of floating point numbers; the representation
  1638. of the yielded numbers may be surprising.
  1639. ``datetime.datetime`` objects can be used for *start* and *stop*, if *step*
  1640. is a ``datetime.timedelta`` object:
  1641. >>> import datetime
  1642. >>> start = datetime.datetime(2019, 1, 1)
  1643. >>> stop = datetime.datetime(2019, 1, 3)
  1644. >>> step = datetime.timedelta(days=1)
  1645. >>> items = iter(numeric_range(start, stop, step))
  1646. >>> next(items)
  1647. datetime.datetime(2019, 1, 1, 0, 0)
  1648. >>> next(items)
  1649. datetime.datetime(2019, 1, 2, 0, 0)
  1650. """
  1651. _EMPTY_HASH = hash(range(0, 0))
  1652. def __init__(self, *args):
  1653. argc = len(args)
  1654. if argc == 1:
  1655. (self._stop,) = args
  1656. self._start = type(self._stop)(0)
  1657. self._step = type(self._stop - self._start)(1)
  1658. elif argc == 2:
  1659. self._start, self._stop = args
  1660. self._step = type(self._stop - self._start)(1)
  1661. elif argc == 3:
  1662. self._start, self._stop, self._step = args
  1663. elif argc == 0:
  1664. raise TypeError(
  1665. 'numeric_range expected at least '
  1666. '1 argument, got {}'.format(argc)
  1667. )
  1668. else:
  1669. raise TypeError(
  1670. 'numeric_range expected at most '
  1671. '3 arguments, got {}'.format(argc)
  1672. )
  1673. self._zero = type(self._step)(0)
  1674. if self._step == self._zero:
  1675. raise ValueError('numeric_range() arg 3 must not be zero')
  1676. self._growing = self._step > self._zero
  1677. def __bool__(self):
  1678. if self._growing:
  1679. return self._start < self._stop
  1680. else:
  1681. return self._start > self._stop
  1682. def __contains__(self, elem):
  1683. if self._growing:
  1684. if self._start <= elem < self._stop:
  1685. return (elem - self._start) % self._step == self._zero
  1686. else:
  1687. if self._start >= elem > self._stop:
  1688. return (self._start - elem) % (-self._step) == self._zero
  1689. return False
  1690. def __eq__(self, other):
  1691. if isinstance(other, numeric_range):
  1692. empty_self = not bool(self)
  1693. empty_other = not bool(other)
  1694. if empty_self or empty_other:
  1695. return empty_self and empty_other # True if both empty
  1696. else:
  1697. return (
  1698. self._start == other._start
  1699. and self._step == other._step
  1700. and self._get_by_index(-1) == other._get_by_index(-1)
  1701. )
  1702. else:
  1703. return False
  1704. def __getitem__(self, key):
  1705. if isinstance(key, int):
  1706. return self._get_by_index(key)
  1707. elif isinstance(key, slice):
  1708. step = self._step if key.step is None else key.step * self._step
  1709. if key.start is None or key.start <= -self._len:
  1710. start = self._start
  1711. elif key.start >= self._len:
  1712. start = self._stop
  1713. else: # -self._len < key.start < self._len
  1714. start = self._get_by_index(key.start)
  1715. if key.stop is None or key.stop >= self._len:
  1716. stop = self._stop
  1717. elif key.stop <= -self._len:
  1718. stop = self._start
  1719. else: # -self._len < key.stop < self._len
  1720. stop = self._get_by_index(key.stop)
  1721. return numeric_range(start, stop, step)
  1722. else:
  1723. raise TypeError(
  1724. 'numeric range indices must be '
  1725. 'integers or slices, not {}'.format(type(key).__name__)
  1726. )
  1727. def __hash__(self):
  1728. if self:
  1729. return hash((self._start, self._get_by_index(-1), self._step))
  1730. else:
  1731. return self._EMPTY_HASH
  1732. def __iter__(self):
  1733. values = (self._start + (n * self._step) for n in count())
  1734. if self._growing:
  1735. return takewhile(partial(gt, self._stop), values)
  1736. else:
  1737. return takewhile(partial(lt, self._stop), values)
  1738. def __len__(self):
  1739. return self._len
  1740. @cached_property
  1741. def _len(self):
  1742. if self._growing:
  1743. start = self._start
  1744. stop = self._stop
  1745. step = self._step
  1746. else:
  1747. start = self._stop
  1748. stop = self._start
  1749. step = -self._step
  1750. distance = stop - start
  1751. if distance <= self._zero:
  1752. return 0
  1753. else: # distance > 0 and step > 0: regular euclidean division
  1754. q, r = divmod(distance, step)
  1755. return int(q) + int(r != self._zero)
  1756. def __reduce__(self):
  1757. return numeric_range, (self._start, self._stop, self._step)
  1758. def __repr__(self):
  1759. if self._step == 1:
  1760. return "numeric_range({}, {})".format(
  1761. repr(self._start), repr(self._stop)
  1762. )
  1763. else:
  1764. return "numeric_range({}, {}, {})".format(
  1765. repr(self._start), repr(self._stop), repr(self._step)
  1766. )
  1767. def __reversed__(self):
  1768. return iter(
  1769. numeric_range(
  1770. self._get_by_index(-1), self._start - self._step, -self._step
  1771. )
  1772. )
  1773. def count(self, value):
  1774. return int(value in self)
  1775. def index(self, value):
  1776. if self._growing:
  1777. if self._start <= value < self._stop:
  1778. q, r = divmod(value - self._start, self._step)
  1779. if r == self._zero:
  1780. return int(q)
  1781. else:
  1782. if self._start >= value > self._stop:
  1783. q, r = divmod(self._start - value, -self._step)
  1784. if r == self._zero:
  1785. return int(q)
  1786. raise ValueError("{} is not in numeric range".format(value))
  1787. def _get_by_index(self, i):
  1788. if i < 0:
  1789. i += self._len
  1790. if i < 0 or i >= self._len:
  1791. raise IndexError("numeric range object index out of range")
  1792. return self._start + i * self._step
  1793. def count_cycle(iterable, n=None):
  1794. """Cycle through the items from *iterable* up to *n* times, yielding
  1795. the number of completed cycles along with each item. If *n* is omitted the
  1796. process repeats indefinitely.
  1797. >>> list(count_cycle('AB', 3))
  1798. [(0, 'A'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')]
  1799. """
  1800. iterable = tuple(iterable)
  1801. if not iterable:
  1802. return iter(())
  1803. counter = count() if n is None else range(n)
  1804. return ((i, item) for i in counter for item in iterable)
  1805. def mark_ends(iterable):
  1806. """Yield 3-tuples of the form ``(is_first, is_last, item)``.
  1807. >>> list(mark_ends('ABC'))
  1808. [(True, False, 'A'), (False, False, 'B'), (False, True, 'C')]
  1809. Use this when looping over an iterable to take special action on its first
  1810. and/or last items:
  1811. >>> iterable = ['Header', 100, 200, 'Footer']
  1812. >>> total = 0
  1813. >>> for is_first, is_last, item in mark_ends(iterable):
  1814. ... if is_first:
  1815. ... continue # Skip the header
  1816. ... if is_last:
  1817. ... continue # Skip the footer
  1818. ... total += item
  1819. >>> print(total)
  1820. 300
  1821. """
  1822. it = iter(iterable)
  1823. try:
  1824. b = next(it)
  1825. except StopIteration:
  1826. return
  1827. try:
  1828. for i in count():
  1829. a = b
  1830. b = next(it)
  1831. yield i == 0, False, a
  1832. except StopIteration:
  1833. yield i == 0, True, a
  1834. def locate(iterable, pred=bool, window_size=None):
  1835. """Yield the index of each item in *iterable* for which *pred* returns
  1836. ``True``.
  1837. *pred* defaults to :func:`bool`, which will select truthy items:
  1838. >>> list(locate([0, 1, 1, 0, 1, 0, 0]))
  1839. [1, 2, 4]
  1840. Set *pred* to a custom function to, e.g., find the indexes for a particular
  1841. item.
  1842. >>> list(locate(['a', 'b', 'c', 'b'], lambda x: x == 'b'))
  1843. [1, 3]
  1844. If *window_size* is given, then the *pred* function will be called with
  1845. that many items. This enables searching for sub-sequences:
  1846. >>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
  1847. >>> pred = lambda *args: args == (1, 2, 3)
  1848. >>> list(locate(iterable, pred=pred, window_size=3))
  1849. [1, 5, 9]
  1850. Use with :func:`seekable` to find indexes and then retrieve the associated
  1851. items:
  1852. >>> from itertools import count
  1853. >>> from more_itertools import seekable
  1854. >>> source = (3 * n + 1 if (n % 2) else n // 2 for n in count())
  1855. >>> it = seekable(source)
  1856. >>> pred = lambda x: x > 100
  1857. >>> indexes = locate(it, pred=pred)
  1858. >>> i = next(indexes)
  1859. >>> it.seek(i)
  1860. >>> next(it)
  1861. 106
  1862. """
  1863. if window_size is None:
  1864. return compress(count(), map(pred, iterable))
  1865. if window_size < 1:
  1866. raise ValueError('window size must be at least 1')
  1867. it = windowed(iterable, window_size, fillvalue=_marker)
  1868. return compress(count(), starmap(pred, it))
  1869. def longest_common_prefix(iterables):
  1870. """Yield elements of the longest common prefix amongst given *iterables*.
  1871. >>> ''.join(longest_common_prefix(['abcd', 'abc', 'abf']))
  1872. 'ab'
  1873. """
  1874. return (c[0] for c in takewhile(all_equal, zip(*iterables)))
  1875. def lstrip(iterable, pred):
  1876. """Yield the items from *iterable*, but strip any from the beginning
  1877. for which *pred* returns ``True``.
  1878. For example, to remove a set of items from the start of an iterable:
  1879. >>> iterable = (None, False, None, 1, 2, None, 3, False, None)
  1880. >>> pred = lambda x: x in {None, False, ''}
  1881. >>> list(lstrip(iterable, pred))
  1882. [1, 2, None, 3, False, None]
  1883. This function is analogous to to :func:`str.lstrip`, and is essentially
  1884. an wrapper for :func:`itertools.dropwhile`.
  1885. """
  1886. return dropwhile(pred, iterable)
  1887. def rstrip(iterable, pred):
  1888. """Yield the items from *iterable*, but strip any from the end
  1889. for which *pred* returns ``True``.
  1890. For example, to remove a set of items from the end of an iterable:
  1891. >>> iterable = (None, False, None, 1, 2, None, 3, False, None)
  1892. >>> pred = lambda x: x in {None, False, ''}
  1893. >>> list(rstrip(iterable, pred))
  1894. [None, False, None, 1, 2, None, 3]
  1895. This function is analogous to :func:`str.rstrip`.
  1896. """
  1897. cache = []
  1898. cache_append = cache.append
  1899. cache_clear = cache.clear
  1900. for x in iterable:
  1901. if pred(x):
  1902. cache_append(x)
  1903. else:
  1904. yield from cache
  1905. cache_clear()
  1906. yield x
  1907. def strip(iterable, pred):
  1908. """Yield the items from *iterable*, but strip any from the
  1909. beginning and end for which *pred* returns ``True``.
  1910. For example, to remove a set of items from both ends of an iterable:
  1911. >>> iterable = (None, False, None, 1, 2, None, 3, False, None)
  1912. >>> pred = lambda x: x in {None, False, ''}
  1913. >>> list(strip(iterable, pred))
  1914. [1, 2, None, 3]
  1915. This function is analogous to :func:`str.strip`.
  1916. """
  1917. return rstrip(lstrip(iterable, pred), pred)
  1918. class islice_extended:
  1919. """An extension of :func:`itertools.islice` that supports negative values
  1920. for *stop*, *start*, and *step*.
  1921. >>> iterable = iter('abcdefgh')
  1922. >>> list(islice_extended(iterable, -4, -1))
  1923. ['e', 'f', 'g']
  1924. Slices with negative values require some caching of *iterable*, but this
  1925. function takes care to minimize the amount of memory required.
  1926. For example, you can use a negative step with an infinite iterator:
  1927. >>> from itertools import count
  1928. >>> list(islice_extended(count(), 110, 99, -2))
  1929. [110, 108, 106, 104, 102, 100]
  1930. You can also use slice notation directly:
  1931. >>> iterable = map(str, count())
  1932. >>> it = islice_extended(iterable)[10:20:2]
  1933. >>> list(it)
  1934. ['10', '12', '14', '16', '18']
  1935. """
  1936. def __init__(self, iterable, *args):
  1937. it = iter(iterable)
  1938. if args:
  1939. self._iterable = _islice_helper(it, slice(*args))
  1940. else:
  1941. self._iterable = it
  1942. def __iter__(self):
  1943. return self
  1944. def __next__(self):
  1945. return next(self._iterable)
  1946. def __getitem__(self, key):
  1947. if isinstance(key, slice):
  1948. return islice_extended(_islice_helper(self._iterable, key))
  1949. raise TypeError('islice_extended.__getitem__ argument must be a slice')
  1950. def _islice_helper(it, s):
  1951. start = s.start
  1952. stop = s.stop
  1953. if s.step == 0:
  1954. raise ValueError('step argument must be a non-zero integer or None.')
  1955. step = s.step or 1
  1956. if step > 0:
  1957. start = 0 if (start is None) else start
  1958. if start < 0:
  1959. # Consume all but the last -start items
  1960. cache = deque(enumerate(it, 1), maxlen=-start)
  1961. len_iter = cache[-1][0] if cache else 0
  1962. # Adjust start to be positive
  1963. i = max(len_iter + start, 0)
  1964. # Adjust stop to be positive
  1965. if stop is None:
  1966. j = len_iter
  1967. elif stop >= 0:
  1968. j = min(stop, len_iter)
  1969. else:
  1970. j = max(len_iter + stop, 0)
  1971. # Slice the cache
  1972. n = j - i
  1973. if n <= 0:
  1974. return
  1975. for index, item in islice(cache, 0, n, step):
  1976. yield item
  1977. elif (stop is not None) and (stop < 0):
  1978. # Advance to the start position
  1979. next(islice(it, start, start), None)
  1980. # When stop is negative, we have to carry -stop items while
  1981. # iterating
  1982. cache = deque(islice(it, -stop), maxlen=-stop)
  1983. for index, item in enumerate(it):
  1984. cached_item = cache.popleft()
  1985. if index % step == 0:
  1986. yield cached_item
  1987. cache.append(item)
  1988. else:
  1989. # When both start and stop are positive we have the normal case
  1990. yield from islice(it, start, stop, step)
  1991. else:
  1992. start = -1 if (start is None) else start
  1993. if (stop is not None) and (stop < 0):
  1994. # Consume all but the last items
  1995. n = -stop - 1
  1996. cache = deque(enumerate(it, 1), maxlen=n)
  1997. len_iter = cache[-1][0] if cache else 0
  1998. # If start and stop are both negative they are comparable and
  1999. # we can just slice. Otherwise we can adjust start to be negative
  2000. # and then slice.
  2001. if start < 0:
  2002. i, j = start, stop
  2003. else:
  2004. i, j = min(start - len_iter, -1), None
  2005. for index, item in list(cache)[i:j:step]:
  2006. yield item
  2007. else:
  2008. # Advance to the stop position
  2009. if stop is not None:
  2010. m = stop + 1
  2011. next(islice(it, m, m), None)
  2012. # stop is positive, so if start is negative they are not comparable
  2013. # and we need the rest of the items.
  2014. if start < 0:
  2015. i = start
  2016. n = None
  2017. # stop is None and start is positive, so we just need items up to
  2018. # the start index.
  2019. elif stop is None:
  2020. i = None
  2021. n = start + 1
  2022. # Both stop and start are positive, so they are comparable.
  2023. else:
  2024. i = None
  2025. n = start - stop
  2026. if n <= 0:
  2027. return
  2028. cache = list(islice(it, n))
  2029. yield from cache[i::step]
  2030. def always_reversible(iterable):
  2031. """An extension of :func:`reversed` that supports all iterables, not
  2032. just those which implement the ``Reversible`` or ``Sequence`` protocols.
  2033. >>> print(*always_reversible(x for x in range(3)))
  2034. 2 1 0
  2035. If the iterable is already reversible, this function returns the
  2036. result of :func:`reversed()`. If the iterable is not reversible,
  2037. this function will cache the remaining items in the iterable and
  2038. yield them in reverse order, which may require significant storage.
  2039. """
  2040. try:
  2041. return reversed(iterable)
  2042. except TypeError:
  2043. return reversed(list(iterable))
  2044. def consecutive_groups(iterable, ordering=lambda x: x):
  2045. """Yield groups of consecutive items using :func:`itertools.groupby`.
  2046. The *ordering* function determines whether two items are adjacent by
  2047. returning their position.
  2048. By default, the ordering function is the identity function. This is
  2049. suitable for finding runs of numbers:
  2050. >>> iterable = [1, 10, 11, 12, 20, 30, 31, 32, 33, 40]
  2051. >>> for group in consecutive_groups(iterable):
  2052. ... print(list(group))
  2053. [1]
  2054. [10, 11, 12]
  2055. [20]
  2056. [30, 31, 32, 33]
  2057. [40]
  2058. For finding runs of adjacent letters, try using the :meth:`index` method
  2059. of a string of letters:
  2060. >>> from string import ascii_lowercase
  2061. >>> iterable = 'abcdfgilmnop'
  2062. >>> ordering = ascii_lowercase.index
  2063. >>> for group in consecutive_groups(iterable, ordering):
  2064. ... print(list(group))
  2065. ['a', 'b', 'c', 'd']
  2066. ['f', 'g']
  2067. ['i']
  2068. ['l', 'm', 'n', 'o', 'p']
  2069. Each group of consecutive items is an iterator that shares it source with
  2070. *iterable*. When an an output group is advanced, the previous group is
  2071. no longer available unless its elements are copied (e.g., into a ``list``).
  2072. >>> iterable = [1, 2, 11, 12, 21, 22]
  2073. >>> saved_groups = []
  2074. >>> for group in consecutive_groups(iterable):
  2075. ... saved_groups.append(list(group)) # Copy group elements
  2076. >>> saved_groups
  2077. [[1, 2], [11, 12], [21, 22]]
  2078. """
  2079. for k, g in groupby(
  2080. enumerate(iterable), key=lambda x: x[0] - ordering(x[1])
  2081. ):
  2082. yield map(itemgetter(1), g)
  2083. def difference(iterable, func=sub, *, initial=None):
  2084. """This function is the inverse of :func:`itertools.accumulate`. By default
  2085. it will compute the first difference of *iterable* using
  2086. :func:`operator.sub`:
  2087. >>> from itertools import accumulate
  2088. >>> iterable = accumulate([0, 1, 2, 3, 4]) # produces 0, 1, 3, 6, 10
  2089. >>> list(difference(iterable))
  2090. [0, 1, 2, 3, 4]
  2091. *func* defaults to :func:`operator.sub`, but other functions can be
  2092. specified. They will be applied as follows::
  2093. A, B, C, D, ... --> A, func(B, A), func(C, B), func(D, C), ...
  2094. For example, to do progressive division:
  2095. >>> iterable = [1, 2, 6, 24, 120]
  2096. >>> func = lambda x, y: x // y
  2097. >>> list(difference(iterable, func))
  2098. [1, 2, 3, 4, 5]
  2099. If the *initial* keyword is set, the first element will be skipped when
  2100. computing successive differences.
  2101. >>> it = [10, 11, 13, 16] # from accumulate([1, 2, 3], initial=10)
  2102. >>> list(difference(it, initial=10))
  2103. [1, 2, 3]
  2104. """
  2105. a, b = tee(iterable)
  2106. try:
  2107. first = [next(b)]
  2108. except StopIteration:
  2109. return iter([])
  2110. if initial is not None:
  2111. first = []
  2112. return chain(first, map(func, b, a))
  2113. class SequenceView(Sequence):
  2114. """Return a read-only view of the sequence object *target*.
  2115. :class:`SequenceView` objects are analogous to Python's built-in
  2116. "dictionary view" types. They provide a dynamic view of a sequence's items,
  2117. meaning that when the sequence updates, so does the view.
  2118. >>> seq = ['0', '1', '2']
  2119. >>> view = SequenceView(seq)
  2120. >>> view
  2121. SequenceView(['0', '1', '2'])
  2122. >>> seq.append('3')
  2123. >>> view
  2124. SequenceView(['0', '1', '2', '3'])
  2125. Sequence views support indexing, slicing, and length queries. They act
  2126. like the underlying sequence, except they don't allow assignment:
  2127. >>> view[1]
  2128. '1'
  2129. >>> view[1:-1]
  2130. ['1', '2']
  2131. >>> len(view)
  2132. 4
  2133. Sequence views are useful as an alternative to copying, as they don't
  2134. require (much) extra storage.
  2135. """
  2136. def __init__(self, target):
  2137. if not isinstance(target, Sequence):
  2138. raise TypeError
  2139. self._target = target
  2140. def __getitem__(self, index):
  2141. return self._target[index]
  2142. def __len__(self):
  2143. return len(self._target)
  2144. def __repr__(self):
  2145. return '{}({})'.format(self.__class__.__name__, repr(self._target))
  2146. class seekable:
  2147. """Wrap an iterator to allow for seeking backward and forward. This
  2148. progressively caches the items in the source iterable so they can be
  2149. re-visited.
  2150. Call :meth:`seek` with an index to seek to that position in the source
  2151. iterable.
  2152. To "reset" an iterator, seek to ``0``:
  2153. >>> from itertools import count
  2154. >>> it = seekable((str(n) for n in count()))
  2155. >>> next(it), next(it), next(it)
  2156. ('0', '1', '2')
  2157. >>> it.seek(0)
  2158. >>> next(it), next(it), next(it)
  2159. ('0', '1', '2')
  2160. >>> next(it)
  2161. '3'
  2162. You can also seek forward:
  2163. >>> it = seekable((str(n) for n in range(20)))
  2164. >>> it.seek(10)
  2165. >>> next(it)
  2166. '10'
  2167. >>> it.relative_seek(-2) # Seeking relative to the current position
  2168. >>> next(it)
  2169. '9'
  2170. >>> it.seek(20) # Seeking past the end of the source isn't a problem
  2171. >>> list(it)
  2172. []
  2173. >>> it.seek(0) # Resetting works even after hitting the end
  2174. >>> next(it), next(it), next(it)
  2175. ('0', '1', '2')
  2176. Call :meth:`peek` to look ahead one item without advancing the iterator:
  2177. >>> it = seekable('1234')
  2178. >>> it.peek()
  2179. '1'
  2180. >>> list(it)
  2181. ['1', '2', '3', '4']
  2182. >>> it.peek(default='empty')
  2183. 'empty'
  2184. Before the iterator is at its end, calling :func:`bool` on it will return
  2185. ``True``. After it will return ``False``:
  2186. >>> it = seekable('5678')
  2187. >>> bool(it)
  2188. True
  2189. >>> list(it)
  2190. ['5', '6', '7', '8']
  2191. >>> bool(it)
  2192. False
  2193. You may view the contents of the cache with the :meth:`elements` method.
  2194. That returns a :class:`SequenceView`, a view that updates automatically:
  2195. >>> it = seekable((str(n) for n in range(10)))
  2196. >>> next(it), next(it), next(it)
  2197. ('0', '1', '2')
  2198. >>> elements = it.elements()
  2199. >>> elements
  2200. SequenceView(['0', '1', '2'])
  2201. >>> next(it)
  2202. '3'
  2203. >>> elements
  2204. SequenceView(['0', '1', '2', '3'])
  2205. By default, the cache grows as the source iterable progresses, so beware of
  2206. wrapping very large or infinite iterables. Supply *maxlen* to limit the
  2207. size of the cache (this of course limits how far back you can seek).
  2208. >>> from itertools import count
  2209. >>> it = seekable((str(n) for n in count()), maxlen=2)
  2210. >>> next(it), next(it), next(it), next(it)
  2211. ('0', '1', '2', '3')
  2212. >>> list(it.elements())
  2213. ['2', '3']
  2214. >>> it.seek(0)
  2215. >>> next(it), next(it), next(it), next(it)
  2216. ('2', '3', '4', '5')
  2217. >>> next(it)
  2218. '6'
  2219. """
  2220. def __init__(self, iterable, maxlen=None):
  2221. self._source = iter(iterable)
  2222. if maxlen is None:
  2223. self._cache = []
  2224. else:
  2225. self._cache = deque([], maxlen)
  2226. self._index = None
  2227. def __iter__(self):
  2228. return self
  2229. def __next__(self):
  2230. if self._index is not None:
  2231. try:
  2232. item = self._cache[self._index]
  2233. except IndexError:
  2234. self._index = None
  2235. else:
  2236. self._index += 1
  2237. return item
  2238. item = next(self._source)
  2239. self._cache.append(item)
  2240. return item
  2241. def __bool__(self):
  2242. try:
  2243. self.peek()
  2244. except StopIteration:
  2245. return False
  2246. return True
  2247. def peek(self, default=_marker):
  2248. try:
  2249. peeked = next(self)
  2250. except StopIteration:
  2251. if default is _marker:
  2252. raise
  2253. return default
  2254. if self._index is None:
  2255. self._index = len(self._cache)
  2256. self._index -= 1
  2257. return peeked
  2258. def elements(self):
  2259. return SequenceView(self._cache)
  2260. def seek(self, index):
  2261. self._index = index
  2262. remainder = index - len(self._cache)
  2263. if remainder > 0:
  2264. consume(self, remainder)
  2265. def relative_seek(self, count):
  2266. index = len(self._cache)
  2267. self.seek(max(index + count, 0))
  2268. class run_length:
  2269. """
  2270. :func:`run_length.encode` compresses an iterable with run-length encoding.
  2271. It yields groups of repeated items with the count of how many times they
  2272. were repeated:
  2273. >>> uncompressed = 'abbcccdddd'
  2274. >>> list(run_length.encode(uncompressed))
  2275. [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
  2276. :func:`run_length.decode` decompresses an iterable that was previously
  2277. compressed with run-length encoding. It yields the items of the
  2278. decompressed iterable:
  2279. >>> compressed = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
  2280. >>> list(run_length.decode(compressed))
  2281. ['a', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'd']
  2282. """
  2283. @staticmethod
  2284. def encode(iterable):
  2285. return ((k, ilen(g)) for k, g in groupby(iterable))
  2286. @staticmethod
  2287. def decode(iterable):
  2288. return chain.from_iterable(repeat(k, n) for k, n in iterable)
  2289. def exactly_n(iterable, n, predicate=bool):
  2290. """Return ``True`` if exactly ``n`` items in the iterable are ``True``
  2291. according to the *predicate* function.
  2292. >>> exactly_n([True, True, False], 2)
  2293. True
  2294. >>> exactly_n([True, True, False], 1)
  2295. False
  2296. >>> exactly_n([0, 1, 2, 3, 4, 5], 3, lambda x: x < 3)
  2297. True
  2298. The iterable will be advanced until ``n + 1`` truthy items are encountered,
  2299. so avoid calling it on infinite iterables.
  2300. """
  2301. return len(take(n + 1, filter(predicate, iterable))) == n
  2302. def circular_shifts(iterable):
  2303. """Return a list of circular shifts of *iterable*.
  2304. >>> circular_shifts(range(4))
  2305. [(0, 1, 2, 3), (1, 2, 3, 0), (2, 3, 0, 1), (3, 0, 1, 2)]
  2306. """
  2307. lst = list(iterable)
  2308. return take(len(lst), windowed(cycle(lst), len(lst)))
  2309. def make_decorator(wrapping_func, result_index=0):
  2310. """Return a decorator version of *wrapping_func*, which is a function that
  2311. modifies an iterable. *result_index* is the position in that function's
  2312. signature where the iterable goes.
  2313. This lets you use itertools on the "production end," i.e. at function
  2314. definition. This can augment what the function returns without changing the
  2315. function's code.
  2316. For example, to produce a decorator version of :func:`chunked`:
  2317. >>> from more_itertools import chunked
  2318. >>> chunker = make_decorator(chunked, result_index=0)
  2319. >>> @chunker(3)
  2320. ... def iter_range(n):
  2321. ... return iter(range(n))
  2322. ...
  2323. >>> list(iter_range(9))
  2324. [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
  2325. To only allow truthy items to be returned:
  2326. >>> truth_serum = make_decorator(filter, result_index=1)
  2327. >>> @truth_serum(bool)
  2328. ... def boolean_test():
  2329. ... return [0, 1, '', ' ', False, True]
  2330. ...
  2331. >>> list(boolean_test())
  2332. [1, ' ', True]
  2333. The :func:`peekable` and :func:`seekable` wrappers make for practical
  2334. decorators:
  2335. >>> from more_itertools import peekable
  2336. >>> peekable_function = make_decorator(peekable)
  2337. >>> @peekable_function()
  2338. ... def str_range(*args):
  2339. ... return (str(x) for x in range(*args))
  2340. ...
  2341. >>> it = str_range(1, 20, 2)
  2342. >>> next(it), next(it), next(it)
  2343. ('1', '3', '5')
  2344. >>> it.peek()
  2345. '7'
  2346. >>> next(it)
  2347. '7'
  2348. """
  2349. # See https://sites.google.com/site/bbayles/index/decorator_factory for
  2350. # notes on how this works.
  2351. def decorator(*wrapping_args, **wrapping_kwargs):
  2352. def outer_wrapper(f):
  2353. def inner_wrapper(*args, **kwargs):
  2354. result = f(*args, **kwargs)
  2355. wrapping_args_ = list(wrapping_args)
  2356. wrapping_args_.insert(result_index, result)
  2357. return wrapping_func(*wrapping_args_, **wrapping_kwargs)
  2358. return inner_wrapper
  2359. return outer_wrapper
  2360. return decorator
  2361. def map_reduce(iterable, keyfunc, valuefunc=None, reducefunc=None):
  2362. """Return a dictionary that maps the items in *iterable* to categories
  2363. defined by *keyfunc*, transforms them with *valuefunc*, and
  2364. then summarizes them by category with *reducefunc*.
  2365. *valuefunc* defaults to the identity function if it is unspecified.
  2366. If *reducefunc* is unspecified, no summarization takes place:
  2367. >>> keyfunc = lambda x: x.upper()
  2368. >>> result = map_reduce('abbccc', keyfunc)
  2369. >>> sorted(result.items())
  2370. [('A', ['a']), ('B', ['b', 'b']), ('C', ['c', 'c', 'c'])]
  2371. Specifying *valuefunc* transforms the categorized items:
  2372. >>> keyfunc = lambda x: x.upper()
  2373. >>> valuefunc = lambda x: 1
  2374. >>> result = map_reduce('abbccc', keyfunc, valuefunc)
  2375. >>> sorted(result.items())
  2376. [('A', [1]), ('B', [1, 1]), ('C', [1, 1, 1])]
  2377. Specifying *reducefunc* summarizes the categorized items:
  2378. >>> keyfunc = lambda x: x.upper()
  2379. >>> valuefunc = lambda x: 1
  2380. >>> reducefunc = sum
  2381. >>> result = map_reduce('abbccc', keyfunc, valuefunc, reducefunc)
  2382. >>> sorted(result.items())
  2383. [('A', 1), ('B', 2), ('C', 3)]
  2384. You may want to filter the input iterable before applying the map/reduce
  2385. procedure:
  2386. >>> all_items = range(30)
  2387. >>> items = [x for x in all_items if 10 <= x <= 20] # Filter
  2388. >>> keyfunc = lambda x: x % 2 # Evens map to 0; odds to 1
  2389. >>> categories = map_reduce(items, keyfunc=keyfunc)
  2390. >>> sorted(categories.items())
  2391. [(0, [10, 12, 14, 16, 18, 20]), (1, [11, 13, 15, 17, 19])]
  2392. >>> summaries = map_reduce(items, keyfunc=keyfunc, reducefunc=sum)
  2393. >>> sorted(summaries.items())
  2394. [(0, 90), (1, 75)]
  2395. Note that all items in the iterable are gathered into a list before the
  2396. summarization step, which may require significant storage.
  2397. The returned object is a :obj:`collections.defaultdict` with the
  2398. ``default_factory`` set to ``None``, such that it behaves like a normal
  2399. dictionary.
  2400. """
  2401. valuefunc = (lambda x: x) if (valuefunc is None) else valuefunc
  2402. ret = defaultdict(list)
  2403. for item in iterable:
  2404. key = keyfunc(item)
  2405. value = valuefunc(item)
  2406. ret[key].append(value)
  2407. if reducefunc is not None:
  2408. for key, value_list in ret.items():
  2409. ret[key] = reducefunc(value_list)
  2410. ret.default_factory = None
  2411. return ret
  2412. def rlocate(iterable, pred=bool, window_size=None):
  2413. """Yield the index of each item in *iterable* for which *pred* returns
  2414. ``True``, starting from the right and moving left.
  2415. *pred* defaults to :func:`bool`, which will select truthy items:
  2416. >>> list(rlocate([0, 1, 1, 0, 1, 0, 0])) # Truthy at 1, 2, and 4
  2417. [4, 2, 1]
  2418. Set *pred* to a custom function to, e.g., find the indexes for a particular
  2419. item:
  2420. >>> iterable = iter('abcb')
  2421. >>> pred = lambda x: x == 'b'
  2422. >>> list(rlocate(iterable, pred))
  2423. [3, 1]
  2424. If *window_size* is given, then the *pred* function will be called with
  2425. that many items. This enables searching for sub-sequences:
  2426. >>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
  2427. >>> pred = lambda *args: args == (1, 2, 3)
  2428. >>> list(rlocate(iterable, pred=pred, window_size=3))
  2429. [9, 5, 1]
  2430. Beware, this function won't return anything for infinite iterables.
  2431. If *iterable* is reversible, ``rlocate`` will reverse it and search from
  2432. the right. Otherwise, it will search from the left and return the results
  2433. in reverse order.
  2434. See :func:`locate` to for other example applications.
  2435. """
  2436. if window_size is None:
  2437. try:
  2438. len_iter = len(iterable)
  2439. return (len_iter - i - 1 for i in locate(reversed(iterable), pred))
  2440. except TypeError:
  2441. pass
  2442. return reversed(list(locate(iterable, pred, window_size)))
  2443. def replace(iterable, pred, substitutes, count=None, window_size=1):
  2444. """Yield the items from *iterable*, replacing the items for which *pred*
  2445. returns ``True`` with the items from the iterable *substitutes*.
  2446. >>> iterable = [1, 1, 0, 1, 1, 0, 1, 1]
  2447. >>> pred = lambda x: x == 0
  2448. >>> substitutes = (2, 3)
  2449. >>> list(replace(iterable, pred, substitutes))
  2450. [1, 1, 2, 3, 1, 1, 2, 3, 1, 1]
  2451. If *count* is given, the number of replacements will be limited:
  2452. >>> iterable = [1, 1, 0, 1, 1, 0, 1, 1, 0]
  2453. >>> pred = lambda x: x == 0
  2454. >>> substitutes = [None]
  2455. >>> list(replace(iterable, pred, substitutes, count=2))
  2456. [1, 1, None, 1, 1, None, 1, 1, 0]
  2457. Use *window_size* to control the number of items passed as arguments to
  2458. *pred*. This allows for locating and replacing subsequences.
  2459. >>> iterable = [0, 1, 2, 5, 0, 1, 2, 5]
  2460. >>> window_size = 3
  2461. >>> pred = lambda *args: args == (0, 1, 2) # 3 items passed to pred
  2462. >>> substitutes = [3, 4] # Splice in these items
  2463. >>> list(replace(iterable, pred, substitutes, window_size=window_size))
  2464. [3, 4, 5, 3, 4, 5]
  2465. """
  2466. if window_size < 1:
  2467. raise ValueError('window_size must be at least 1')
  2468. # Save the substitutes iterable, since it's used more than once
  2469. substitutes = tuple(substitutes)
  2470. # Add padding such that the number of windows matches the length of the
  2471. # iterable
  2472. it = chain(iterable, [_marker] * (window_size - 1))
  2473. windows = windowed(it, window_size)
  2474. n = 0
  2475. for w in windows:
  2476. # If the current window matches our predicate (and we haven't hit
  2477. # our maximum number of replacements), splice in the substitutes
  2478. # and then consume the following windows that overlap with this one.
  2479. # For example, if the iterable is (0, 1, 2, 3, 4...)
  2480. # and the window size is 2, we have (0, 1), (1, 2), (2, 3)...
  2481. # If the predicate matches on (0, 1), we need to zap (0, 1) and (1, 2)
  2482. if pred(*w):
  2483. if (count is None) or (n < count):
  2484. n += 1
  2485. yield from substitutes
  2486. consume(windows, window_size - 1)
  2487. continue
  2488. # If there was no match (or we've reached the replacement limit),
  2489. # yield the first item from the window.
  2490. if w and (w[0] is not _marker):
  2491. yield w[0]
  2492. def partitions(iterable):
  2493. """Yield all possible order-preserving partitions of *iterable*.
  2494. >>> iterable = 'abc'
  2495. >>> for part in partitions(iterable):
  2496. ... print([''.join(p) for p in part])
  2497. ['abc']
  2498. ['a', 'bc']
  2499. ['ab', 'c']
  2500. ['a', 'b', 'c']
  2501. This is unrelated to :func:`partition`.
  2502. """
  2503. sequence = list(iterable)
  2504. n = len(sequence)
  2505. for i in powerset(range(1, n)):
  2506. yield [sequence[i:j] for i, j in zip((0,) + i, i + (n,))]
  2507. def set_partitions(iterable, k=None):
  2508. """
  2509. Yield the set partitions of *iterable* into *k* parts. Set partitions are
  2510. not order-preserving.
  2511. >>> iterable = 'abc'
  2512. >>> for part in set_partitions(iterable, 2):
  2513. ... print([''.join(p) for p in part])
  2514. ['a', 'bc']
  2515. ['ab', 'c']
  2516. ['b', 'ac']
  2517. If *k* is not given, every set partition is generated.
  2518. >>> iterable = 'abc'
  2519. >>> for part in set_partitions(iterable):
  2520. ... print([''.join(p) for p in part])
  2521. ['abc']
  2522. ['a', 'bc']
  2523. ['ab', 'c']
  2524. ['b', 'ac']
  2525. ['a', 'b', 'c']
  2526. """
  2527. L = list(iterable)
  2528. n = len(L)
  2529. if k is not None:
  2530. if k < 1:
  2531. raise ValueError(
  2532. "Can't partition in a negative or zero number of groups"
  2533. )
  2534. elif k > n:
  2535. return
  2536. def set_partitions_helper(L, k):
  2537. n = len(L)
  2538. if k == 1:
  2539. yield [L]
  2540. elif n == k:
  2541. yield [[s] for s in L]
  2542. else:
  2543. e, *M = L
  2544. for p in set_partitions_helper(M, k - 1):
  2545. yield [[e], *p]
  2546. for p in set_partitions_helper(M, k):
  2547. for i in range(len(p)):
  2548. yield p[:i] + [[e] + p[i]] + p[i + 1 :]
  2549. if k is None:
  2550. for k in range(1, n + 1):
  2551. yield from set_partitions_helper(L, k)
  2552. else:
  2553. yield from set_partitions_helper(L, k)
  2554. class time_limited:
  2555. """
  2556. Yield items from *iterable* until *limit_seconds* have passed.
  2557. If the time limit expires before all items have been yielded, the
  2558. ``timed_out`` parameter will be set to ``True``.
  2559. >>> from time import sleep
  2560. >>> def generator():
  2561. ... yield 1
  2562. ... yield 2
  2563. ... sleep(0.2)
  2564. ... yield 3
  2565. >>> iterable = time_limited(0.1, generator())
  2566. >>> list(iterable)
  2567. [1, 2]
  2568. >>> iterable.timed_out
  2569. True
  2570. Note that the time is checked before each item is yielded, and iteration
  2571. stops if the time elapsed is greater than *limit_seconds*. If your time
  2572. limit is 1 second, but it takes 2 seconds to generate the first item from
  2573. the iterable, the function will run for 2 seconds and not yield anything.
  2574. As a special case, when *limit_seconds* is zero, the iterator never
  2575. returns anything.
  2576. """
  2577. def __init__(self, limit_seconds, iterable):
  2578. if limit_seconds < 0:
  2579. raise ValueError('limit_seconds must be positive')
  2580. self.limit_seconds = limit_seconds
  2581. self._iterable = iter(iterable)
  2582. self._start_time = monotonic()
  2583. self.timed_out = False
  2584. def __iter__(self):
  2585. return self
  2586. def __next__(self):
  2587. if self.limit_seconds == 0:
  2588. self.timed_out = True
  2589. raise StopIteration
  2590. item = next(self._iterable)
  2591. if monotonic() - self._start_time > self.limit_seconds:
  2592. self.timed_out = True
  2593. raise StopIteration
  2594. return item
  2595. def only(iterable, default=None, too_long=None):
  2596. """If *iterable* has only one item, return it.
  2597. If it has zero items, return *default*.
  2598. If it has more than one item, raise the exception given by *too_long*,
  2599. which is ``ValueError`` by default.
  2600. >>> only([], default='missing')
  2601. 'missing'
  2602. >>> only([1])
  2603. 1
  2604. >>> only([1, 2]) # doctest: +IGNORE_EXCEPTION_DETAIL
  2605. Traceback (most recent call last):
  2606. ...
  2607. ValueError: Expected exactly one item in iterable, but got 1, 2,
  2608. and perhaps more.'
  2609. >>> only([1, 2], too_long=TypeError) # doctest: +IGNORE_EXCEPTION_DETAIL
  2610. Traceback (most recent call last):
  2611. ...
  2612. TypeError
  2613. Note that :func:`only` attempts to advance *iterable* twice to ensure there
  2614. is only one item. See :func:`spy` or :func:`peekable` to check
  2615. iterable contents less destructively.
  2616. """
  2617. it = iter(iterable)
  2618. first_value = next(it, default)
  2619. try:
  2620. second_value = next(it)
  2621. except StopIteration:
  2622. pass
  2623. else:
  2624. msg = (
  2625. 'Expected exactly one item in iterable, but got {!r}, {!r}, '
  2626. 'and perhaps more.'.format(first_value, second_value)
  2627. )
  2628. raise too_long or ValueError(msg)
  2629. return first_value
  2630. def _ichunk(iterable, n):
  2631. cache = deque()
  2632. chunk = islice(iterable, n)
  2633. def generator():
  2634. while True:
  2635. if cache:
  2636. yield cache.popleft()
  2637. else:
  2638. try:
  2639. item = next(chunk)
  2640. except StopIteration:
  2641. return
  2642. else:
  2643. yield item
  2644. def materialize_next(n=1):
  2645. # if n not specified materialize everything
  2646. if n is None:
  2647. cache.extend(chunk)
  2648. return len(cache)
  2649. to_cache = n - len(cache)
  2650. # materialize up to n
  2651. if to_cache > 0:
  2652. cache.extend(islice(chunk, to_cache))
  2653. # return number materialized up to n
  2654. return min(n, len(cache))
  2655. return (generator(), materialize_next)
  2656. def ichunked(iterable, n):
  2657. """Break *iterable* into sub-iterables with *n* elements each.
  2658. :func:`ichunked` is like :func:`chunked`, but it yields iterables
  2659. instead of lists.
  2660. If the sub-iterables are read in order, the elements of *iterable*
  2661. won't be stored in memory.
  2662. If they are read out of order, :func:`itertools.tee` is used to cache
  2663. elements as necessary.
  2664. >>> from itertools import count
  2665. >>> all_chunks = ichunked(count(), 4)
  2666. >>> c_1, c_2, c_3 = next(all_chunks), next(all_chunks), next(all_chunks)
  2667. >>> list(c_2) # c_1's elements have been cached; c_3's haven't been
  2668. [4, 5, 6, 7]
  2669. >>> list(c_1)
  2670. [0, 1, 2, 3]
  2671. >>> list(c_3)
  2672. [8, 9, 10, 11]
  2673. """
  2674. iterable = iter(iterable)
  2675. while True:
  2676. # Create new chunk
  2677. chunk, materialize_next = _ichunk(iterable, n)
  2678. # Check to see whether we're at the end of the source iterable
  2679. if not materialize_next():
  2680. return
  2681. yield chunk
  2682. # Fill previous chunk's cache
  2683. materialize_next(None)
  2684. def iequals(*iterables):
  2685. """Return ``True`` if all given *iterables* are equal to each other,
  2686. which means that they contain the same elements in the same order.
  2687. The function is useful for comparing iterables of different data types
  2688. or iterables that do not support equality checks.
  2689. >>> iequals("abc", ['a', 'b', 'c'], ('a', 'b', 'c'), iter("abc"))
  2690. True
  2691. >>> iequals("abc", "acb")
  2692. False
  2693. Not to be confused with :func:`all_equal`, which checks whether all
  2694. elements of iterable are equal to each other.
  2695. """
  2696. return all(map(all_equal, zip_longest(*iterables, fillvalue=object())))
  2697. def distinct_combinations(iterable, r):
  2698. """Yield the distinct combinations of *r* items taken from *iterable*.
  2699. >>> list(distinct_combinations([0, 0, 1], 2))
  2700. [(0, 0), (0, 1)]
  2701. Equivalent to ``set(combinations(iterable))``, except duplicates are not
  2702. generated and thrown away. For larger input sequences this is much more
  2703. efficient.
  2704. """
  2705. if r < 0:
  2706. raise ValueError('r must be non-negative')
  2707. elif r == 0:
  2708. yield ()
  2709. return
  2710. pool = tuple(iterable)
  2711. generators = [unique_everseen(enumerate(pool), key=itemgetter(1))]
  2712. current_combo = [None] * r
  2713. level = 0
  2714. while generators:
  2715. try:
  2716. cur_idx, p = next(generators[-1])
  2717. except StopIteration:
  2718. generators.pop()
  2719. level -= 1
  2720. continue
  2721. current_combo[level] = p
  2722. if level + 1 == r:
  2723. yield tuple(current_combo)
  2724. else:
  2725. generators.append(
  2726. unique_everseen(
  2727. enumerate(pool[cur_idx + 1 :], cur_idx + 1),
  2728. key=itemgetter(1),
  2729. )
  2730. )
  2731. level += 1
  2732. def filter_except(validator, iterable, *exceptions):
  2733. """Yield the items from *iterable* for which the *validator* function does
  2734. not raise one of the specified *exceptions*.
  2735. *validator* is called for each item in *iterable*.
  2736. It should be a function that accepts one argument and raises an exception
  2737. if that item is not valid.
  2738. >>> iterable = ['1', '2', 'three', '4', None]
  2739. >>> list(filter_except(int, iterable, ValueError, TypeError))
  2740. ['1', '2', '4']
  2741. If an exception other than one given by *exceptions* is raised by
  2742. *validator*, it is raised like normal.
  2743. """
  2744. for item in iterable:
  2745. try:
  2746. validator(item)
  2747. except exceptions:
  2748. pass
  2749. else:
  2750. yield item
  2751. def map_except(function, iterable, *exceptions):
  2752. """Transform each item from *iterable* with *function* and yield the
  2753. result, unless *function* raises one of the specified *exceptions*.
  2754. *function* is called to transform each item in *iterable*.
  2755. It should accept one argument.
  2756. >>> iterable = ['1', '2', 'three', '4', None]
  2757. >>> list(map_except(int, iterable, ValueError, TypeError))
  2758. [1, 2, 4]
  2759. If an exception other than one given by *exceptions* is raised by
  2760. *function*, it is raised like normal.
  2761. """
  2762. for item in iterable:
  2763. try:
  2764. yield function(item)
  2765. except exceptions:
  2766. pass
  2767. def map_if(iterable, pred, func, func_else=lambda x: x):
  2768. """Evaluate each item from *iterable* using *pred*. If the result is
  2769. equivalent to ``True``, transform the item with *func* and yield it.
  2770. Otherwise, transform the item with *func_else* and yield it.
  2771. *pred*, *func*, and *func_else* should each be functions that accept
  2772. one argument. By default, *func_else* is the identity function.
  2773. >>> from math import sqrt
  2774. >>> iterable = list(range(-5, 5))
  2775. >>> iterable
  2776. [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
  2777. >>> list(map_if(iterable, lambda x: x > 3, lambda x: 'toobig'))
  2778. [-5, -4, -3, -2, -1, 0, 1, 2, 3, 'toobig']
  2779. >>> list(map_if(iterable, lambda x: x >= 0,
  2780. ... lambda x: f'{sqrt(x):.2f}', lambda x: None))
  2781. [None, None, None, None, None, '0.00', '1.00', '1.41', '1.73', '2.00']
  2782. """
  2783. for item in iterable:
  2784. yield func(item) if pred(item) else func_else(item)
  2785. def _sample_unweighted(iterable, k):
  2786. # Implementation of "Algorithm L" from the 1994 paper by Kim-Hung Li:
  2787. # "Reservoir-Sampling Algorithms of Time Complexity O(n(1+log(N/n)))".
  2788. # Fill up the reservoir (collection of samples) with the first `k` samples
  2789. reservoir = take(k, iterable)
  2790. # Generate random number that's the largest in a sample of k U(0,1) numbers
  2791. # Largest order statistic: https://en.wikipedia.org/wiki/Order_statistic
  2792. W = exp(log(random()) / k)
  2793. # The number of elements to skip before changing the reservoir is a random
  2794. # number with a geometric distribution. Sample it using random() and logs.
  2795. next_index = k + floor(log(random()) / log(1 - W))
  2796. for index, element in enumerate(iterable, k):
  2797. if index == next_index:
  2798. reservoir[randrange(k)] = element
  2799. # The new W is the largest in a sample of k U(0, `old_W`) numbers
  2800. W *= exp(log(random()) / k)
  2801. next_index += floor(log(random()) / log(1 - W)) + 1
  2802. return reservoir
  2803. def _sample_weighted(iterable, k, weights):
  2804. # Implementation of "A-ExpJ" from the 2006 paper by Efraimidis et al. :
  2805. # "Weighted random sampling with a reservoir".
  2806. # Log-transform for numerical stability for weights that are small/large
  2807. weight_keys = (log(random()) / weight for weight in weights)
  2808. # Fill up the reservoir (collection of samples) with the first `k`
  2809. # weight-keys and elements, then heapify the list.
  2810. reservoir = take(k, zip(weight_keys, iterable))
  2811. heapify(reservoir)
  2812. # The number of jumps before changing the reservoir is a random variable
  2813. # with an exponential distribution. Sample it using random() and logs.
  2814. smallest_weight_key, _ = reservoir[0]
  2815. weights_to_skip = log(random()) / smallest_weight_key
  2816. for weight, element in zip(weights, iterable):
  2817. if weight >= weights_to_skip:
  2818. # The notation here is consistent with the paper, but we store
  2819. # the weight-keys in log-space for better numerical stability.
  2820. smallest_weight_key, _ = reservoir[0]
  2821. t_w = exp(weight * smallest_weight_key)
  2822. r_2 = uniform(t_w, 1) # generate U(t_w, 1)
  2823. weight_key = log(r_2) / weight
  2824. heapreplace(reservoir, (weight_key, element))
  2825. smallest_weight_key, _ = reservoir[0]
  2826. weights_to_skip = log(random()) / smallest_weight_key
  2827. else:
  2828. weights_to_skip -= weight
  2829. # Equivalent to [element for weight_key, element in sorted(reservoir)]
  2830. return [heappop(reservoir)[1] for _ in range(k)]
  2831. def sample(iterable, k, weights=None):
  2832. """Return a *k*-length list of elements chosen (without replacement)
  2833. from the *iterable*. Like :func:`random.sample`, but works on iterables
  2834. of unknown length.
  2835. >>> iterable = range(100)
  2836. >>> sample(iterable, 5) # doctest: +SKIP
  2837. [81, 60, 96, 16, 4]
  2838. An iterable with *weights* may also be given:
  2839. >>> iterable = range(100)
  2840. >>> weights = (i * i + 1 for i in range(100))
  2841. >>> sampled = sample(iterable, 5, weights=weights) # doctest: +SKIP
  2842. [79, 67, 74, 66, 78]
  2843. The algorithm can also be used to generate weighted random permutations.
  2844. The relative weight of each item determines the probability that it
  2845. appears late in the permutation.
  2846. >>> data = "abcdefgh"
  2847. >>> weights = range(1, len(data) + 1)
  2848. >>> sample(data, k=len(data), weights=weights) # doctest: +SKIP
  2849. ['c', 'a', 'b', 'e', 'g', 'd', 'h', 'f']
  2850. """
  2851. if k == 0:
  2852. return []
  2853. iterable = iter(iterable)
  2854. if weights is None:
  2855. return _sample_unweighted(iterable, k)
  2856. else:
  2857. weights = iter(weights)
  2858. return _sample_weighted(iterable, k, weights)
  2859. def is_sorted(iterable, key=None, reverse=False, strict=False):
  2860. """Returns ``True`` if the items of iterable are in sorted order, and
  2861. ``False`` otherwise. *key* and *reverse* have the same meaning that they do
  2862. in the built-in :func:`sorted` function.
  2863. >>> is_sorted(['1', '2', '3', '4', '5'], key=int)
  2864. True
  2865. >>> is_sorted([5, 4, 3, 1, 2], reverse=True)
  2866. False
  2867. If *strict*, tests for strict sorting, that is, returns ``False`` if equal
  2868. elements are found:
  2869. >>> is_sorted([1, 2, 2])
  2870. True
  2871. >>> is_sorted([1, 2, 2], strict=True)
  2872. False
  2873. The function returns ``False`` after encountering the first out-of-order
  2874. item. If there are no out-of-order items, the iterable is exhausted.
  2875. """
  2876. compare = (le if reverse else ge) if strict else (lt if reverse else gt)
  2877. it = iterable if key is None else map(key, iterable)
  2878. return not any(starmap(compare, pairwise(it)))
  2879. class AbortThread(BaseException):
  2880. pass
  2881. class callback_iter:
  2882. """Convert a function that uses callbacks to an iterator.
  2883. Let *func* be a function that takes a `callback` keyword argument.
  2884. For example:
  2885. >>> def func(callback=None):
  2886. ... for i, c in [(1, 'a'), (2, 'b'), (3, 'c')]:
  2887. ... if callback:
  2888. ... callback(i, c)
  2889. ... return 4
  2890. Use ``with callback_iter(func)`` to get an iterator over the parameters
  2891. that are delivered to the callback.
  2892. >>> with callback_iter(func) as it:
  2893. ... for args, kwargs in it:
  2894. ... print(args)
  2895. (1, 'a')
  2896. (2, 'b')
  2897. (3, 'c')
  2898. The function will be called in a background thread. The ``done`` property
  2899. indicates whether it has completed execution.
  2900. >>> it.done
  2901. True
  2902. If it completes successfully, its return value will be available
  2903. in the ``result`` property.
  2904. >>> it.result
  2905. 4
  2906. Notes:
  2907. * If the function uses some keyword argument besides ``callback``, supply
  2908. *callback_kwd*.
  2909. * If it finished executing, but raised an exception, accessing the
  2910. ``result`` property will raise the same exception.
  2911. * If it hasn't finished executing, accessing the ``result``
  2912. property from within the ``with`` block will raise ``RuntimeError``.
  2913. * If it hasn't finished executing, accessing the ``result`` property from
  2914. outside the ``with`` block will raise a
  2915. ``more_itertools.AbortThread`` exception.
  2916. * Provide *wait_seconds* to adjust how frequently the it is polled for
  2917. output.
  2918. """
  2919. def __init__(self, func, callback_kwd='callback', wait_seconds=0.1):
  2920. self._func = func
  2921. self._callback_kwd = callback_kwd
  2922. self._aborted = False
  2923. self._future = None
  2924. self._wait_seconds = wait_seconds
  2925. # Lazily import concurrent.future
  2926. self._executor = __import__(
  2927. 'concurrent.futures'
  2928. ).futures.ThreadPoolExecutor(max_workers=1)
  2929. self._iterator = self._reader()
  2930. def __enter__(self):
  2931. return self
  2932. def __exit__(self, exc_type, exc_value, traceback):
  2933. self._aborted = True
  2934. self._executor.shutdown()
  2935. def __iter__(self):
  2936. return self
  2937. def __next__(self):
  2938. return next(self._iterator)
  2939. @property
  2940. def done(self):
  2941. if self._future is None:
  2942. return False
  2943. return self._future.done()
  2944. @property
  2945. def result(self):
  2946. if not self.done:
  2947. raise RuntimeError('Function has not yet completed')
  2948. return self._future.result()
  2949. def _reader(self):
  2950. q = Queue()
  2951. def callback(*args, **kwargs):
  2952. if self._aborted:
  2953. raise AbortThread('canceled by user')
  2954. q.put((args, kwargs))
  2955. self._future = self._executor.submit(
  2956. self._func, **{self._callback_kwd: callback}
  2957. )
  2958. while True:
  2959. try:
  2960. item = q.get(timeout=self._wait_seconds)
  2961. except Empty:
  2962. pass
  2963. else:
  2964. q.task_done()
  2965. yield item
  2966. if self._future.done():
  2967. break
  2968. remaining = []
  2969. while True:
  2970. try:
  2971. item = q.get_nowait()
  2972. except Empty:
  2973. break
  2974. else:
  2975. q.task_done()
  2976. remaining.append(item)
  2977. q.join()
  2978. yield from remaining
  2979. def windowed_complete(iterable, n):
  2980. """
  2981. Yield ``(beginning, middle, end)`` tuples, where:
  2982. * Each ``middle`` has *n* items from *iterable*
  2983. * Each ``beginning`` has the items before the ones in ``middle``
  2984. * Each ``end`` has the items after the ones in ``middle``
  2985. >>> iterable = range(7)
  2986. >>> n = 3
  2987. >>> for beginning, middle, end in windowed_complete(iterable, n):
  2988. ... print(beginning, middle, end)
  2989. () (0, 1, 2) (3, 4, 5, 6)
  2990. (0,) (1, 2, 3) (4, 5, 6)
  2991. (0, 1) (2, 3, 4) (5, 6)
  2992. (0, 1, 2) (3, 4, 5) (6,)
  2993. (0, 1, 2, 3) (4, 5, 6) ()
  2994. Note that *n* must be at least 0 and most equal to the length of
  2995. *iterable*.
  2996. This function will exhaust the iterable and may require significant
  2997. storage.
  2998. """
  2999. if n < 0:
  3000. raise ValueError('n must be >= 0')
  3001. seq = tuple(iterable)
  3002. size = len(seq)
  3003. if n > size:
  3004. raise ValueError('n must be <= len(seq)')
  3005. for i in range(size - n + 1):
  3006. beginning = seq[:i]
  3007. middle = seq[i : i + n]
  3008. end = seq[i + n :]
  3009. yield beginning, middle, end
  3010. def all_unique(iterable, key=None):
  3011. """
  3012. Returns ``True`` if all the elements of *iterable* are unique (no two
  3013. elements are equal).
  3014. >>> all_unique('ABCB')
  3015. False
  3016. If a *key* function is specified, it will be used to make comparisons.
  3017. >>> all_unique('ABCb')
  3018. True
  3019. >>> all_unique('ABCb', str.lower)
  3020. False
  3021. The function returns as soon as the first non-unique element is
  3022. encountered. Iterables with a mix of hashable and unhashable items can
  3023. be used, but the function will be slower for unhashable items.
  3024. """
  3025. seenset = set()
  3026. seenset_add = seenset.add
  3027. seenlist = []
  3028. seenlist_add = seenlist.append
  3029. for element in map(key, iterable) if key else iterable:
  3030. try:
  3031. if element in seenset:
  3032. return False
  3033. seenset_add(element)
  3034. except TypeError:
  3035. if element in seenlist:
  3036. return False
  3037. seenlist_add(element)
  3038. return True
  3039. def nth_product(index, *args):
  3040. """Equivalent to ``list(product(*args))[index]``.
  3041. The products of *args* can be ordered lexicographically.
  3042. :func:`nth_product` computes the product at sort position *index* without
  3043. computing the previous products.
  3044. >>> nth_product(8, range(2), range(2), range(2), range(2))
  3045. (1, 0, 0, 0)
  3046. ``IndexError`` will be raised if the given *index* is invalid.
  3047. """
  3048. pools = list(map(tuple, reversed(args)))
  3049. ns = list(map(len, pools))
  3050. c = reduce(mul, ns)
  3051. if index < 0:
  3052. index += c
  3053. if not 0 <= index < c:
  3054. raise IndexError
  3055. result = []
  3056. for pool, n in zip(pools, ns):
  3057. result.append(pool[index % n])
  3058. index //= n
  3059. return tuple(reversed(result))
  3060. def nth_permutation(iterable, r, index):
  3061. """Equivalent to ``list(permutations(iterable, r))[index]```
  3062. The subsequences of *iterable* that are of length *r* where order is
  3063. important can be ordered lexicographically. :func:`nth_permutation`
  3064. computes the subsequence at sort position *index* directly, without
  3065. computing the previous subsequences.
  3066. >>> nth_permutation('ghijk', 2, 5)
  3067. ('h', 'i')
  3068. ``ValueError`` will be raised If *r* is negative or greater than the length
  3069. of *iterable*.
  3070. ``IndexError`` will be raised if the given *index* is invalid.
  3071. """
  3072. pool = list(iterable)
  3073. n = len(pool)
  3074. if r is None or r == n:
  3075. r, c = n, factorial(n)
  3076. elif not 0 <= r < n:
  3077. raise ValueError
  3078. else:
  3079. c = perm(n, r)
  3080. assert c > 0 # factortial(n)>0, and r<n so perm(n,r) is never zero
  3081. if index < 0:
  3082. index += c
  3083. if not 0 <= index < c:
  3084. raise IndexError
  3085. result = [0] * r
  3086. q = index * factorial(n) // c if r < n else index
  3087. for d in range(1, n + 1):
  3088. q, i = divmod(q, d)
  3089. if 0 <= n - d < r:
  3090. result[n - d] = i
  3091. if q == 0:
  3092. break
  3093. return tuple(map(pool.pop, result))
  3094. def nth_combination_with_replacement(iterable, r, index):
  3095. """Equivalent to
  3096. ``list(combinations_with_replacement(iterable, r))[index]``.
  3097. The subsequences with repetition of *iterable* that are of length *r* can
  3098. be ordered lexicographically. :func:`nth_combination_with_replacement`
  3099. computes the subsequence at sort position *index* directly, without
  3100. computing the previous subsequences with replacement.
  3101. >>> nth_combination_with_replacement(range(5), 3, 5)
  3102. (0, 1, 1)
  3103. ``ValueError`` will be raised If *r* is negative or greater than the length
  3104. of *iterable*.
  3105. ``IndexError`` will be raised if the given *index* is invalid.
  3106. """
  3107. pool = tuple(iterable)
  3108. n = len(pool)
  3109. if (r < 0) or (r > n):
  3110. raise ValueError
  3111. c = comb(n + r - 1, r)
  3112. if index < 0:
  3113. index += c
  3114. if (index < 0) or (index >= c):
  3115. raise IndexError
  3116. result = []
  3117. i = 0
  3118. while r:
  3119. r -= 1
  3120. while n >= 0:
  3121. num_combs = comb(n + r - 1, r)
  3122. if index < num_combs:
  3123. break
  3124. n -= 1
  3125. i += 1
  3126. index -= num_combs
  3127. result.append(pool[i])
  3128. return tuple(result)
  3129. def value_chain(*args):
  3130. """Yield all arguments passed to the function in the same order in which
  3131. they were passed. If an argument itself is iterable then iterate over its
  3132. values.
  3133. >>> list(value_chain(1, 2, 3, [4, 5, 6]))
  3134. [1, 2, 3, 4, 5, 6]
  3135. Binary and text strings are not considered iterable and are emitted
  3136. as-is:
  3137. >>> list(value_chain('12', '34', ['56', '78']))
  3138. ['12', '34', '56', '78']
  3139. Pre- or postpend a single element to an iterable:
  3140. >>> list(value_chain(1, [2, 3, 4, 5, 6]))
  3141. [1, 2, 3, 4, 5, 6]
  3142. >>> list(value_chain([1, 2, 3, 4, 5], 6))
  3143. [1, 2, 3, 4, 5, 6]
  3144. Multiple levels of nesting are not flattened.
  3145. """
  3146. for value in args:
  3147. if isinstance(value, (str, bytes)):
  3148. yield value
  3149. continue
  3150. try:
  3151. yield from value
  3152. except TypeError:
  3153. yield value
  3154. def product_index(element, *args):
  3155. """Equivalent to ``list(product(*args)).index(element)``
  3156. The products of *args* can be ordered lexicographically.
  3157. :func:`product_index` computes the first index of *element* without
  3158. computing the previous products.
  3159. >>> product_index([8, 2], range(10), range(5))
  3160. 42
  3161. ``ValueError`` will be raised if the given *element* isn't in the product
  3162. of *args*.
  3163. """
  3164. index = 0
  3165. for x, pool in zip_longest(element, args, fillvalue=_marker):
  3166. if x is _marker or pool is _marker:
  3167. raise ValueError('element is not a product of args')
  3168. pool = tuple(pool)
  3169. index = index * len(pool) + pool.index(x)
  3170. return index
  3171. def combination_index(element, iterable):
  3172. """Equivalent to ``list(combinations(iterable, r)).index(element)``
  3173. The subsequences of *iterable* that are of length *r* can be ordered
  3174. lexicographically. :func:`combination_index` computes the index of the
  3175. first *element*, without computing the previous combinations.
  3176. >>> combination_index('adf', 'abcdefg')
  3177. 10
  3178. ``ValueError`` will be raised if the given *element* isn't one of the
  3179. combinations of *iterable*.
  3180. """
  3181. element = enumerate(element)
  3182. k, y = next(element, (None, None))
  3183. if k is None:
  3184. return 0
  3185. indexes = []
  3186. pool = enumerate(iterable)
  3187. for n, x in pool:
  3188. if x == y:
  3189. indexes.append(n)
  3190. tmp, y = next(element, (None, None))
  3191. if tmp is None:
  3192. break
  3193. else:
  3194. k = tmp
  3195. else:
  3196. raise ValueError('element is not a combination of iterable')
  3197. n, _ = last(pool, default=(n, None))
  3198. # Python versions below 3.8 don't have math.comb
  3199. index = 1
  3200. for i, j in enumerate(reversed(indexes), start=1):
  3201. j = n - j
  3202. if i <= j:
  3203. index += comb(j, i)
  3204. return comb(n + 1, k + 1) - index
  3205. def combination_with_replacement_index(element, iterable):
  3206. """Equivalent to
  3207. ``list(combinations_with_replacement(iterable, r)).index(element)``
  3208. The subsequences with repetition of *iterable* that are of length *r* can
  3209. be ordered lexicographically. :func:`combination_with_replacement_index`
  3210. computes the index of the first *element*, without computing the previous
  3211. combinations with replacement.
  3212. >>> combination_with_replacement_index('adf', 'abcdefg')
  3213. 20
  3214. ``ValueError`` will be raised if the given *element* isn't one of the
  3215. combinations with replacement of *iterable*.
  3216. """
  3217. element = tuple(element)
  3218. l = len(element)
  3219. element = enumerate(element)
  3220. k, y = next(element, (None, None))
  3221. if k is None:
  3222. return 0
  3223. indexes = []
  3224. pool = tuple(iterable)
  3225. for n, x in enumerate(pool):
  3226. while x == y:
  3227. indexes.append(n)
  3228. tmp, y = next(element, (None, None))
  3229. if tmp is None:
  3230. break
  3231. else:
  3232. k = tmp
  3233. if y is None:
  3234. break
  3235. else:
  3236. raise ValueError(
  3237. 'element is not a combination with replacement of iterable'
  3238. )
  3239. n = len(pool)
  3240. occupations = [0] * n
  3241. for p in indexes:
  3242. occupations[p] += 1
  3243. index = 0
  3244. cumulative_sum = 0
  3245. for k in range(1, n):
  3246. cumulative_sum += occupations[k - 1]
  3247. j = l + n - 1 - k - cumulative_sum
  3248. i = n - k
  3249. if i <= j:
  3250. index += comb(j, i)
  3251. return index
  3252. def permutation_index(element, iterable):
  3253. """Equivalent to ``list(permutations(iterable, r)).index(element)```
  3254. The subsequences of *iterable* that are of length *r* where order is
  3255. important can be ordered lexicographically. :func:`permutation_index`
  3256. computes the index of the first *element* directly, without computing
  3257. the previous permutations.
  3258. >>> permutation_index([1, 3, 2], range(5))
  3259. 19
  3260. ``ValueError`` will be raised if the given *element* isn't one of the
  3261. permutations of *iterable*.
  3262. """
  3263. index = 0
  3264. pool = list(iterable)
  3265. for i, x in zip(range(len(pool), -1, -1), element):
  3266. r = pool.index(x)
  3267. index = index * i + r
  3268. del pool[r]
  3269. return index
  3270. class countable:
  3271. """Wrap *iterable* and keep a count of how many items have been consumed.
  3272. The ``items_seen`` attribute starts at ``0`` and increments as the iterable
  3273. is consumed:
  3274. >>> iterable = map(str, range(10))
  3275. >>> it = countable(iterable)
  3276. >>> it.items_seen
  3277. 0
  3278. >>> next(it), next(it)
  3279. ('0', '1')
  3280. >>> list(it)
  3281. ['2', '3', '4', '5', '6', '7', '8', '9']
  3282. >>> it.items_seen
  3283. 10
  3284. """
  3285. def __init__(self, iterable):
  3286. self._it = iter(iterable)
  3287. self.items_seen = 0
  3288. def __iter__(self):
  3289. return self
  3290. def __next__(self):
  3291. item = next(self._it)
  3292. self.items_seen += 1
  3293. return item
  3294. def chunked_even(iterable, n):
  3295. """Break *iterable* into lists of approximately length *n*.
  3296. Items are distributed such the lengths of the lists differ by at most
  3297. 1 item.
  3298. >>> iterable = [1, 2, 3, 4, 5, 6, 7]
  3299. >>> n = 3
  3300. >>> list(chunked_even(iterable, n)) # List lengths: 3, 2, 2
  3301. [[1, 2, 3], [4, 5], [6, 7]]
  3302. >>> list(chunked(iterable, n)) # List lengths: 3, 3, 1
  3303. [[1, 2, 3], [4, 5, 6], [7]]
  3304. """
  3305. iterable = iter(iterable)
  3306. # Initialize a buffer to process the chunks while keeping
  3307. # some back to fill any underfilled chunks
  3308. min_buffer = (n - 1) * (n - 2)
  3309. buffer = list(islice(iterable, min_buffer))
  3310. # Append items until we have a completed chunk
  3311. for _ in islice(map(buffer.append, iterable), n, None, n):
  3312. yield buffer[:n]
  3313. del buffer[:n]
  3314. # Check if any chunks need addition processing
  3315. if not buffer:
  3316. return
  3317. length = len(buffer)
  3318. # Chunks are either size `full_size <= n` or `partial_size = full_size - 1`
  3319. q, r = divmod(length, n)
  3320. num_lists = q + (1 if r > 0 else 0)
  3321. q, r = divmod(length, num_lists)
  3322. full_size = q + (1 if r > 0 else 0)
  3323. partial_size = full_size - 1
  3324. num_full = length - partial_size * num_lists
  3325. # Yield chunks of full size
  3326. partial_start_idx = num_full * full_size
  3327. if full_size > 0:
  3328. for i in range(0, partial_start_idx, full_size):
  3329. yield buffer[i : i + full_size]
  3330. # Yield chunks of partial size
  3331. if partial_size > 0:
  3332. for i in range(partial_start_idx, length, partial_size):
  3333. yield buffer[i : i + partial_size]
  3334. def zip_broadcast(*objects, scalar_types=(str, bytes), strict=False):
  3335. """A version of :func:`zip` that "broadcasts" any scalar
  3336. (i.e., non-iterable) items into output tuples.
  3337. >>> iterable_1 = [1, 2, 3]
  3338. >>> iterable_2 = ['a', 'b', 'c']
  3339. >>> scalar = '_'
  3340. >>> list(zip_broadcast(iterable_1, iterable_2, scalar))
  3341. [(1, 'a', '_'), (2, 'b', '_'), (3, 'c', '_')]
  3342. The *scalar_types* keyword argument determines what types are considered
  3343. scalar. It is set to ``(str, bytes)`` by default. Set it to ``None`` to
  3344. treat strings and byte strings as iterable:
  3345. >>> list(zip_broadcast('abc', 0, 'xyz', scalar_types=None))
  3346. [('a', 0, 'x'), ('b', 0, 'y'), ('c', 0, 'z')]
  3347. If the *strict* keyword argument is ``True``, then
  3348. ``UnequalIterablesError`` will be raised if any of the iterables have
  3349. different lengths.
  3350. """
  3351. def is_scalar(obj):
  3352. if scalar_types and isinstance(obj, scalar_types):
  3353. return True
  3354. try:
  3355. iter(obj)
  3356. except TypeError:
  3357. return True
  3358. else:
  3359. return False
  3360. size = len(objects)
  3361. if not size:
  3362. return
  3363. new_item = [None] * size
  3364. iterables, iterable_positions = [], []
  3365. for i, obj in enumerate(objects):
  3366. if is_scalar(obj):
  3367. new_item[i] = obj
  3368. else:
  3369. iterables.append(iter(obj))
  3370. iterable_positions.append(i)
  3371. if not iterables:
  3372. yield tuple(objects)
  3373. return
  3374. zipper = _zip_equal if strict else zip
  3375. for item in zipper(*iterables):
  3376. for i, new_item[i] in zip(iterable_positions, item):
  3377. pass
  3378. yield tuple(new_item)
  3379. def unique_in_window(iterable, n, key=None):
  3380. """Yield the items from *iterable* that haven't been seen recently.
  3381. *n* is the size of the lookback window.
  3382. >>> iterable = [0, 1, 0, 2, 3, 0]
  3383. >>> n = 3
  3384. >>> list(unique_in_window(iterable, n))
  3385. [0, 1, 2, 3, 0]
  3386. The *key* function, if provided, will be used to determine uniqueness:
  3387. >>> list(unique_in_window('abAcda', 3, key=lambda x: x.lower()))
  3388. ['a', 'b', 'c', 'd', 'a']
  3389. The items in *iterable* must be hashable.
  3390. """
  3391. if n <= 0:
  3392. raise ValueError('n must be greater than 0')
  3393. window = deque(maxlen=n)
  3394. counts = defaultdict(int)
  3395. use_key = key is not None
  3396. for item in iterable:
  3397. if len(window) == n:
  3398. to_discard = window[0]
  3399. if counts[to_discard] == 1:
  3400. del counts[to_discard]
  3401. else:
  3402. counts[to_discard] -= 1
  3403. k = key(item) if use_key else item
  3404. if k not in counts:
  3405. yield item
  3406. counts[k] += 1
  3407. window.append(k)
  3408. def duplicates_everseen(iterable, key=None):
  3409. """Yield duplicate elements after their first appearance.
  3410. >>> list(duplicates_everseen('mississippi'))
  3411. ['s', 'i', 's', 's', 'i', 'p', 'i']
  3412. >>> list(duplicates_everseen('AaaBbbCccAaa', str.lower))
  3413. ['a', 'a', 'b', 'b', 'c', 'c', 'A', 'a', 'a']
  3414. This function is analogous to :func:`unique_everseen` and is subject to
  3415. the same performance considerations.
  3416. """
  3417. seen_set = set()
  3418. seen_list = []
  3419. use_key = key is not None
  3420. for element in iterable:
  3421. k = key(element) if use_key else element
  3422. try:
  3423. if k not in seen_set:
  3424. seen_set.add(k)
  3425. else:
  3426. yield element
  3427. except TypeError:
  3428. if k not in seen_list:
  3429. seen_list.append(k)
  3430. else:
  3431. yield element
  3432. def duplicates_justseen(iterable, key=None):
  3433. """Yields serially-duplicate elements after their first appearance.
  3434. >>> list(duplicates_justseen('mississippi'))
  3435. ['s', 's', 'p']
  3436. >>> list(duplicates_justseen('AaaBbbCccAaa', str.lower))
  3437. ['a', 'a', 'b', 'b', 'c', 'c', 'a', 'a']
  3438. This function is analogous to :func:`unique_justseen`.
  3439. """
  3440. return flatten(g for _, g in groupby(iterable, key) for _ in g)
  3441. def classify_unique(iterable, key=None):
  3442. """Classify each element in terms of its uniqueness.
  3443. For each element in the input iterable, return a 3-tuple consisting of:
  3444. 1. The element itself
  3445. 2. ``False`` if the element is equal to the one preceding it in the input,
  3446. ``True`` otherwise (i.e. the equivalent of :func:`unique_justseen`)
  3447. 3. ``False`` if this element has been seen anywhere in the input before,
  3448. ``True`` otherwise (i.e. the equivalent of :func:`unique_everseen`)
  3449. >>> list(classify_unique('otto')) # doctest: +NORMALIZE_WHITESPACE
  3450. [('o', True, True),
  3451. ('t', True, True),
  3452. ('t', False, False),
  3453. ('o', True, False)]
  3454. This function is analogous to :func:`unique_everseen` and is subject to
  3455. the same performance considerations.
  3456. """
  3457. seen_set = set()
  3458. seen_list = []
  3459. use_key = key is not None
  3460. previous = None
  3461. for i, element in enumerate(iterable):
  3462. k = key(element) if use_key else element
  3463. is_unique_justseen = not i or previous != k
  3464. previous = k
  3465. is_unique_everseen = False
  3466. try:
  3467. if k not in seen_set:
  3468. seen_set.add(k)
  3469. is_unique_everseen = True
  3470. except TypeError:
  3471. if k not in seen_list:
  3472. seen_list.append(k)
  3473. is_unique_everseen = True
  3474. yield element, is_unique_justseen, is_unique_everseen
  3475. def minmax(iterable_or_value, *others, key=None, default=_marker):
  3476. """Returns both the smallest and largest items in an iterable
  3477. or the largest of two or more arguments.
  3478. >>> minmax([3, 1, 5])
  3479. (1, 5)
  3480. >>> minmax(4, 2, 6)
  3481. (2, 6)
  3482. If a *key* function is provided, it will be used to transform the input
  3483. items for comparison.
  3484. >>> minmax([5, 30], key=str) # '30' sorts before '5'
  3485. (30, 5)
  3486. If a *default* value is provided, it will be returned if there are no
  3487. input items.
  3488. >>> minmax([], default=(0, 0))
  3489. (0, 0)
  3490. Otherwise ``ValueError`` is raised.
  3491. This function is based on the
  3492. `recipe <http://code.activestate.com/recipes/577916/>`__ by
  3493. Raymond Hettinger and takes care to minimize the number of comparisons
  3494. performed.
  3495. """
  3496. iterable = (iterable_or_value, *others) if others else iterable_or_value
  3497. it = iter(iterable)
  3498. try:
  3499. lo = hi = next(it)
  3500. except StopIteration as exc:
  3501. if default is _marker:
  3502. raise ValueError(
  3503. '`minmax()` argument is an empty iterable. '
  3504. 'Provide a `default` value to suppress this error.'
  3505. ) from exc
  3506. return default
  3507. # Different branches depending on the presence of key. This saves a lot
  3508. # of unimportant copies which would slow the "key=None" branch
  3509. # significantly down.
  3510. if key is None:
  3511. for x, y in zip_longest(it, it, fillvalue=lo):
  3512. if y < x:
  3513. x, y = y, x
  3514. if x < lo:
  3515. lo = x
  3516. if hi < y:
  3517. hi = y
  3518. else:
  3519. lo_key = hi_key = key(lo)
  3520. for x, y in zip_longest(it, it, fillvalue=lo):
  3521. x_key, y_key = key(x), key(y)
  3522. if y_key < x_key:
  3523. x, y, x_key, y_key = y, x, y_key, x_key
  3524. if x_key < lo_key:
  3525. lo, lo_key = x, x_key
  3526. if hi_key < y_key:
  3527. hi, hi_key = y, y_key
  3528. return lo, hi
  3529. def constrained_batches(
  3530. iterable, max_size, max_count=None, get_len=len, strict=True
  3531. ):
  3532. """Yield batches of items from *iterable* with a combined size limited by
  3533. *max_size*.
  3534. >>> iterable = [b'12345', b'123', b'12345678', b'1', b'1', b'12', b'1']
  3535. >>> list(constrained_batches(iterable, 10))
  3536. [(b'12345', b'123'), (b'12345678', b'1', b'1'), (b'12', b'1')]
  3537. If a *max_count* is supplied, the number of items per batch is also
  3538. limited:
  3539. >>> iterable = [b'12345', b'123', b'12345678', b'1', b'1', b'12', b'1']
  3540. >>> list(constrained_batches(iterable, 10, max_count = 2))
  3541. [(b'12345', b'123'), (b'12345678', b'1'), (b'1', b'12'), (b'1',)]
  3542. If a *get_len* function is supplied, use that instead of :func:`len` to
  3543. determine item size.
  3544. If *strict* is ``True``, raise ``ValueError`` if any single item is bigger
  3545. than *max_size*. Otherwise, allow single items to exceed *max_size*.
  3546. """
  3547. if max_size <= 0:
  3548. raise ValueError('maximum size must be greater than zero')
  3549. batch = []
  3550. batch_size = 0
  3551. batch_count = 0
  3552. for item in iterable:
  3553. item_len = get_len(item)
  3554. if strict and item_len > max_size:
  3555. raise ValueError('item size exceeds maximum size')
  3556. reached_count = batch_count == max_count
  3557. reached_size = item_len + batch_size > max_size
  3558. if batch_count and (reached_size or reached_count):
  3559. yield tuple(batch)
  3560. batch.clear()
  3561. batch_size = 0
  3562. batch_count = 0
  3563. batch.append(item)
  3564. batch_size += item_len
  3565. batch_count += 1
  3566. if batch:
  3567. yield tuple(batch)
  3568. def gray_product(*iterables):
  3569. """Like :func:`itertools.product`, but return tuples in an order such
  3570. that only one element in the generated tuple changes from one iteration
  3571. to the next.
  3572. >>> list(gray_product('AB','CD'))
  3573. [('A', 'C'), ('B', 'C'), ('B', 'D'), ('A', 'D')]
  3574. This function consumes all of the input iterables before producing output.
  3575. If any of the input iterables have fewer than two items, ``ValueError``
  3576. is raised.
  3577. For information on the algorithm, see
  3578. `this section <https://www-cs-faculty.stanford.edu/~knuth/fasc2a.ps.gz>`__
  3579. of Donald Knuth's *The Art of Computer Programming*.
  3580. """
  3581. all_iterables = tuple(tuple(x) for x in iterables)
  3582. iterable_count = len(all_iterables)
  3583. for iterable in all_iterables:
  3584. if len(iterable) < 2:
  3585. raise ValueError("each iterable must have two or more items")
  3586. # This is based on "Algorithm H" from section 7.2.1.1, page 20.
  3587. # a holds the indexes of the source iterables for the n-tuple to be yielded
  3588. # f is the array of "focus pointers"
  3589. # o is the array of "directions"
  3590. a = [0] * iterable_count
  3591. f = list(range(iterable_count + 1))
  3592. o = [1] * iterable_count
  3593. while True:
  3594. yield tuple(all_iterables[i][a[i]] for i in range(iterable_count))
  3595. j = f[0]
  3596. f[0] = 0
  3597. if j == iterable_count:
  3598. break
  3599. a[j] = a[j] + o[j]
  3600. if a[j] == 0 or a[j] == len(all_iterables[j]) - 1:
  3601. o[j] = -o[j]
  3602. f[j] = f[j + 1]
  3603. f[j + 1] = j + 1
  3604. def partial_product(*iterables):
  3605. """Yields tuples containing one item from each iterator, with subsequent
  3606. tuples changing a single item at a time by advancing each iterator until it
  3607. is exhausted. This sequence guarantees every value in each iterable is
  3608. output at least once without generating all possible combinations.
  3609. This may be useful, for example, when testing an expensive function.
  3610. >>> list(partial_product('AB', 'C', 'DEF'))
  3611. [('A', 'C', 'D'), ('B', 'C', 'D'), ('B', 'C', 'E'), ('B', 'C', 'F')]
  3612. """
  3613. iterators = list(map(iter, iterables))
  3614. try:
  3615. prod = [next(it) for it in iterators]
  3616. except StopIteration:
  3617. return
  3618. yield tuple(prod)
  3619. for i, it in enumerate(iterators):
  3620. for prod[i] in it:
  3621. yield tuple(prod)
  3622. def takewhile_inclusive(predicate, iterable):
  3623. """A variant of :func:`takewhile` that yields one additional element.
  3624. >>> list(takewhile_inclusive(lambda x: x < 5, [1, 4, 6, 4, 1]))
  3625. [1, 4, 6]
  3626. :func:`takewhile` would return ``[1, 4]``.
  3627. """
  3628. for x in iterable:
  3629. yield x
  3630. if not predicate(x):
  3631. break
  3632. def outer_product(func, xs, ys, *args, **kwargs):
  3633. """A generalized outer product that applies a binary function to all
  3634. pairs of items. Returns a 2D matrix with ``len(xs)`` rows and ``len(ys)``
  3635. columns.
  3636. Also accepts ``*args`` and ``**kwargs`` that are passed to ``func``.
  3637. Multiplication table:
  3638. >>> list(outer_product(mul, range(1, 4), range(1, 6)))
  3639. [(1, 2, 3, 4, 5), (2, 4, 6, 8, 10), (3, 6, 9, 12, 15)]
  3640. Cross tabulation:
  3641. >>> xs = ['A', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B']
  3642. >>> ys = ['X', 'X', 'X', 'Y', 'Z', 'Z', 'Y', 'Y', 'Z', 'Z']
  3643. >>> rows = list(zip(xs, ys))
  3644. >>> count_rows = lambda x, y: rows.count((x, y))
  3645. >>> list(outer_product(count_rows, sorted(set(xs)), sorted(set(ys))))
  3646. [(2, 3, 0), (1, 0, 4)]
  3647. Usage with ``*args`` and ``**kwargs``:
  3648. >>> animals = ['cat', 'wolf', 'mouse']
  3649. >>> list(outer_product(min, animals, animals, key=len))
  3650. [('cat', 'cat', 'cat'), ('cat', 'wolf', 'wolf'), ('cat', 'wolf', 'mouse')]
  3651. """
  3652. ys = tuple(ys)
  3653. return batched(
  3654. starmap(lambda x, y: func(x, y, *args, **kwargs), product(xs, ys)),
  3655. n=len(ys),
  3656. )
  3657. def iter_suppress(iterable, *exceptions):
  3658. """Yield each of the items from *iterable*. If the iteration raises one of
  3659. the specified *exceptions*, that exception will be suppressed and iteration
  3660. will stop.
  3661. >>> from itertools import chain
  3662. >>> def breaks_at_five(x):
  3663. ... while True:
  3664. ... if x >= 5:
  3665. ... raise RuntimeError
  3666. ... yield x
  3667. ... x += 1
  3668. >>> it_1 = iter_suppress(breaks_at_five(1), RuntimeError)
  3669. >>> it_2 = iter_suppress(breaks_at_five(2), RuntimeError)
  3670. >>> list(chain(it_1, it_2))
  3671. [1, 2, 3, 4, 2, 3, 4]
  3672. """
  3673. try:
  3674. yield from iterable
  3675. except exceptions:
  3676. return
  3677. def filter_map(func, iterable):
  3678. """Apply *func* to every element of *iterable*, yielding only those which
  3679. are not ``None``.
  3680. >>> elems = ['1', 'a', '2', 'b', '3']
  3681. >>> list(filter_map(lambda s: int(s) if s.isnumeric() else None, elems))
  3682. [1, 2, 3]
  3683. """
  3684. for x in iterable:
  3685. y = func(x)
  3686. if y is not None:
  3687. yield y
  3688. def powerset_of_sets(iterable):
  3689. """Yields all possible subsets of the iterable.
  3690. >>> list(powerset_of_sets([1, 2, 3])) # doctest: +SKIP
  3691. [set(), {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}]
  3692. >>> list(powerset_of_sets([1, 1, 0])) # doctest: +SKIP
  3693. [set(), {1}, {0}, {0, 1}]
  3694. :func:`powerset_of_sets` takes care to minimize the number
  3695. of hash operations performed.
  3696. """
  3697. sets = tuple(map(set, dict.fromkeys(map(frozenset, zip(iterable)))))
  3698. for r in range(len(sets) + 1):
  3699. yield from starmap(set().union, combinations(sets, r))
  3700. def join_mappings(**field_to_map):
  3701. """
  3702. Joins multiple mappings together using their common keys.
  3703. >>> user_scores = {'elliot': 50, 'claris': 60}
  3704. >>> user_times = {'elliot': 30, 'claris': 40}
  3705. >>> join_mappings(score=user_scores, time=user_times)
  3706. {'elliot': {'score': 50, 'time': 30}, 'claris': {'score': 60, 'time': 40}}
  3707. """
  3708. ret = defaultdict(dict)
  3709. for field_name, mapping in field_to_map.items():
  3710. for key, value in mapping.items():
  3711. ret[key][field_name] = value
  3712. return dict(ret)
  3713. def _complex_sumprod(v1, v2):
  3714. """High precision sumprod() for complex numbers.
  3715. Used by :func:`dft` and :func:`idft`.
  3716. """
  3717. r1 = chain((p.real for p in v1), (-p.imag for p in v1))
  3718. r2 = chain((q.real for q in v2), (q.imag for q in v2))
  3719. i1 = chain((p.real for p in v1), (p.imag for p in v1))
  3720. i2 = chain((q.imag for q in v2), (q.real for q in v2))
  3721. return complex(_fsumprod(r1, r2), _fsumprod(i1, i2))
  3722. def dft(xarr):
  3723. """Discrete Fourier Tranform. *xarr* is a sequence of complex numbers.
  3724. Yields the components of the corresponding transformed output vector.
  3725. >>> import cmath
  3726. >>> xarr = [1, 2-1j, -1j, -1+2j]
  3727. >>> Xarr = [2, -2-2j, -2j, 4+4j]
  3728. >>> all(map(cmath.isclose, dft(xarr), Xarr))
  3729. True
  3730. See :func:`idft` for the inverse Discrete Fourier Transform.
  3731. """
  3732. N = len(xarr)
  3733. roots_of_unity = [e ** (n / N * tau * -1j) for n in range(N)]
  3734. for k in range(N):
  3735. coeffs = [roots_of_unity[k * n % N] for n in range(N)]
  3736. yield _complex_sumprod(xarr, coeffs)
  3737. def idft(Xarr):
  3738. """Inverse Discrete Fourier Tranform. *Xarr* is a sequence of
  3739. complex numbers. Yields the components of the corresponding
  3740. inverse-transformed output vector.
  3741. >>> import cmath
  3742. >>> xarr = [1, 2-1j, -1j, -1+2j]
  3743. >>> Xarr = [2, -2-2j, -2j, 4+4j]
  3744. >>> all(map(cmath.isclose, idft(Xarr), xarr))
  3745. True
  3746. See :func:`dft` for the Discrete Fourier Transform.
  3747. """
  3748. N = len(Xarr)
  3749. roots_of_unity = [e ** (n / N * tau * 1j) for n in range(N)]
  3750. for k in range(N):
  3751. coeffs = [roots_of_unity[k * n % N] for n in range(N)]
  3752. yield _complex_sumprod(Xarr, coeffs) / N
  3753. def doublestarmap(func, iterable):
  3754. """Apply *func* to every item of *iterable* by dictionary unpacking
  3755. the item into *func*.
  3756. The difference between :func:`itertools.starmap` and :func:`doublestarmap`
  3757. parallels the distinction between ``func(*a)`` and ``func(**a)``.
  3758. >>> iterable = [{'a': 1, 'b': 2}, {'a': 40, 'b': 60}]
  3759. >>> list(doublestarmap(lambda a, b: a + b, iterable))
  3760. [3, 100]
  3761. ``TypeError`` will be raised if *func*'s signature doesn't match the
  3762. mapping contained in *iterable* or if *iterable* does not contain mappings.
  3763. """
  3764. for item in iterable:
  3765. yield func(**item)