more.py 140 KB

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