more.py 150 KB

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