more.py 150 KB

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