iterables.py 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172
  1. from collections import Counter, defaultdict, OrderedDict
  2. from itertools import (
  3. chain, combinations, combinations_with_replacement, cycle, islice,
  4. permutations, product, groupby
  5. )
  6. # For backwards compatibility
  7. from itertools import product as cartes # noqa: F401
  8. from operator import gt
  9. # this is the logical location of these functions
  10. from sympy.utilities.enumerative import (
  11. multiset_partitions_taocp, list_visitor, MultisetPartitionTraverser)
  12. from sympy.utilities.misc import as_int
  13. from sympy.utilities.decorator import deprecated
  14. def is_palindromic(s, i=0, j=None):
  15. """
  16. Return True if the sequence is the same from left to right as it
  17. is from right to left in the whole sequence (default) or in the
  18. Python slice ``s[i: j]``; else False.
  19. Examples
  20. ========
  21. >>> from sympy.utilities.iterables import is_palindromic
  22. >>> is_palindromic([1, 0, 1])
  23. True
  24. >>> is_palindromic('abcbb')
  25. False
  26. >>> is_palindromic('abcbb', 1)
  27. False
  28. Normal Python slicing is performed in place so there is no need to
  29. create a slice of the sequence for testing:
  30. >>> is_palindromic('abcbb', 1, -1)
  31. True
  32. >>> is_palindromic('abcbb', -4, -1)
  33. True
  34. See Also
  35. ========
  36. sympy.ntheory.digits.is_palindromic: tests integers
  37. """
  38. i, j, _ = slice(i, j).indices(len(s))
  39. m = (j - i)//2
  40. # if length is odd, middle element will be ignored
  41. return all(s[i + k] == s[j - 1 - k] for k in range(m))
  42. def flatten(iterable, levels=None, cls=None): # noqa: F811
  43. """
  44. Recursively denest iterable containers.
  45. >>> from sympy import flatten
  46. >>> flatten([1, 2, 3])
  47. [1, 2, 3]
  48. >>> flatten([1, 2, [3]])
  49. [1, 2, 3]
  50. >>> flatten([1, [2, 3], [4, 5]])
  51. [1, 2, 3, 4, 5]
  52. >>> flatten([1.0, 2, (1, None)])
  53. [1.0, 2, 1, None]
  54. If you want to denest only a specified number of levels of
  55. nested containers, then set ``levels`` flag to the desired
  56. number of levels::
  57. >>> ls = [[(-2, -1), (1, 2)], [(0, 0)]]
  58. >>> flatten(ls, levels=1)
  59. [(-2, -1), (1, 2), (0, 0)]
  60. If cls argument is specified, it will only flatten instances of that
  61. class, for example:
  62. >>> from sympy import Basic, S
  63. >>> class MyOp(Basic):
  64. ... pass
  65. ...
  66. >>> flatten([MyOp(S(1), MyOp(S(2), S(3)))], cls=MyOp)
  67. [1, 2, 3]
  68. adapted from https://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks
  69. """
  70. from sympy.tensor.array import NDimArray
  71. if levels is not None:
  72. if not levels:
  73. return iterable
  74. elif levels > 0:
  75. levels -= 1
  76. else:
  77. raise ValueError(
  78. "expected non-negative number of levels, got %s" % levels)
  79. if cls is None:
  80. def reducible(x):
  81. return is_sequence(x, set)
  82. else:
  83. def reducible(x):
  84. return isinstance(x, cls)
  85. result = []
  86. for el in iterable:
  87. if reducible(el):
  88. if hasattr(el, 'args') and not isinstance(el, NDimArray):
  89. el = el.args
  90. result.extend(flatten(el, levels=levels, cls=cls))
  91. else:
  92. result.append(el)
  93. return result
  94. def unflatten(iter, n=2):
  95. """Group ``iter`` into tuples of length ``n``. Raise an error if
  96. the length of ``iter`` is not a multiple of ``n``.
  97. """
  98. if n < 1 or len(iter) % n:
  99. raise ValueError('iter length is not a multiple of %i' % n)
  100. return list(zip(*(iter[i::n] for i in range(n))))
  101. def reshape(seq, how):
  102. """Reshape the sequence according to the template in ``how``.
  103. Examples
  104. ========
  105. >>> from sympy.utilities import reshape
  106. >>> seq = list(range(1, 9))
  107. >>> reshape(seq, [4]) # lists of 4
  108. [[1, 2, 3, 4], [5, 6, 7, 8]]
  109. >>> reshape(seq, (4,)) # tuples of 4
  110. [(1, 2, 3, 4), (5, 6, 7, 8)]
  111. >>> reshape(seq, (2, 2)) # tuples of 4
  112. [(1, 2, 3, 4), (5, 6, 7, 8)]
  113. >>> reshape(seq, (2, [2])) # (i, i, [i, i])
  114. [(1, 2, [3, 4]), (5, 6, [7, 8])]
  115. >>> reshape(seq, ((2,), [2])) # etc....
  116. [((1, 2), [3, 4]), ((5, 6), [7, 8])]
  117. >>> reshape(seq, (1, [2], 1))
  118. [(1, [2, 3], 4), (5, [6, 7], 8)]
  119. >>> reshape(tuple(seq), ([[1], 1, (2,)],))
  120. (([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],))
  121. >>> reshape(tuple(seq), ([1], 1, (2,)))
  122. (([1], 2, (3, 4)), ([5], 6, (7, 8)))
  123. >>> reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)])
  124. [[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]]
  125. """
  126. m = sum(flatten(how))
  127. n, rem = divmod(len(seq), m)
  128. if m < 0 or rem:
  129. raise ValueError('template must sum to positive number '
  130. 'that divides the length of the sequence')
  131. i = 0
  132. container = type(how)
  133. rv = [None]*n
  134. for k in range(len(rv)):
  135. _rv = []
  136. for hi in how:
  137. if isinstance(hi, int):
  138. _rv.extend(seq[i: i + hi])
  139. i += hi
  140. else:
  141. n = sum(flatten(hi))
  142. hi_type = type(hi)
  143. _rv.append(hi_type(reshape(seq[i: i + n], hi)[0]))
  144. i += n
  145. rv[k] = container(_rv)
  146. return type(seq)(rv)
  147. def group(seq, multiple=True):
  148. """
  149. Splits a sequence into a list of lists of equal, adjacent elements.
  150. Examples
  151. ========
  152. >>> from sympy import group
  153. >>> group([1, 1, 1, 2, 2, 3])
  154. [[1, 1, 1], [2, 2], [3]]
  155. >>> group([1, 1, 1, 2, 2, 3], multiple=False)
  156. [(1, 3), (2, 2), (3, 1)]
  157. >>> group([1, 1, 3, 2, 2, 1], multiple=False)
  158. [(1, 2), (3, 1), (2, 2), (1, 1)]
  159. See Also
  160. ========
  161. multiset
  162. """
  163. if multiple:
  164. return [(list(g)) for _, g in groupby(seq)]
  165. return [(k, len(list(g))) for k, g in groupby(seq)]
  166. def _iproduct2(iterable1, iterable2):
  167. '''Cartesian product of two possibly infinite iterables'''
  168. it1 = iter(iterable1)
  169. it2 = iter(iterable2)
  170. elems1 = []
  171. elems2 = []
  172. sentinel = object()
  173. def append(it, elems):
  174. e = next(it, sentinel)
  175. if e is not sentinel:
  176. elems.append(e)
  177. n = 0
  178. append(it1, elems1)
  179. append(it2, elems2)
  180. while n <= len(elems1) + len(elems2):
  181. for m in range(n-len(elems1)+1, len(elems2)):
  182. yield (elems1[n-m], elems2[m])
  183. n += 1
  184. append(it1, elems1)
  185. append(it2, elems2)
  186. def iproduct(*iterables):
  187. '''
  188. Cartesian product of iterables.
  189. Generator of the Cartesian product of iterables. This is analogous to
  190. itertools.product except that it works with infinite iterables and will
  191. yield any item from the infinite product eventually.
  192. Examples
  193. ========
  194. >>> from sympy.utilities.iterables import iproduct
  195. >>> sorted(iproduct([1,2], [3,4]))
  196. [(1, 3), (1, 4), (2, 3), (2, 4)]
  197. With an infinite iterator:
  198. >>> from sympy import S
  199. >>> (3,) in iproduct(S.Integers)
  200. True
  201. >>> (3, 4) in iproduct(S.Integers, S.Integers)
  202. True
  203. .. seealso::
  204. `itertools.product
  205. <https://docs.python.org/3/library/itertools.html#itertools.product>`_
  206. '''
  207. if len(iterables) == 0:
  208. yield ()
  209. return
  210. elif len(iterables) == 1:
  211. for e in iterables[0]:
  212. yield (e,)
  213. elif len(iterables) == 2:
  214. yield from _iproduct2(*iterables)
  215. else:
  216. first, others = iterables[0], iterables[1:]
  217. for ef, eo in _iproduct2(first, iproduct(*others)):
  218. yield (ef,) + eo
  219. def multiset(seq):
  220. """Return the hashable sequence in multiset form with values being the
  221. multiplicity of the item in the sequence.
  222. Examples
  223. ========
  224. >>> from sympy.utilities.iterables import multiset
  225. >>> multiset('mississippi')
  226. {'i': 4, 'm': 1, 'p': 2, 's': 4}
  227. See Also
  228. ========
  229. group
  230. """
  231. return dict(Counter(seq).items())
  232. def ibin(n, bits=None, str=False):
  233. """Return a list of length ``bits`` corresponding to the binary value
  234. of ``n`` with small bits to the right (last). If bits is omitted, the
  235. length will be the number required to represent ``n``. If the bits are
  236. desired in reversed order, use the ``[::-1]`` slice of the returned list.
  237. If a sequence of all bits-length lists starting from ``[0, 0,..., 0]``
  238. through ``[1, 1, ..., 1]`` are desired, pass a non-integer for bits, e.g.
  239. ``'all'``.
  240. If the bit *string* is desired pass ``str=True``.
  241. Examples
  242. ========
  243. >>> from sympy.utilities.iterables import ibin
  244. >>> ibin(2)
  245. [1, 0]
  246. >>> ibin(2, 4)
  247. [0, 0, 1, 0]
  248. If all lists corresponding to 0 to 2**n - 1, pass a non-integer
  249. for bits:
  250. >>> bits = 2
  251. >>> for i in ibin(2, 'all'):
  252. ... print(i)
  253. (0, 0)
  254. (0, 1)
  255. (1, 0)
  256. (1, 1)
  257. If a bit string is desired of a given length, use str=True:
  258. >>> n = 123
  259. >>> bits = 10
  260. >>> ibin(n, bits, str=True)
  261. '0001111011'
  262. >>> ibin(n, bits, str=True)[::-1] # small bits left
  263. '1101111000'
  264. >>> list(ibin(3, 'all', str=True))
  265. ['000', '001', '010', '011', '100', '101', '110', '111']
  266. """
  267. if n < 0:
  268. raise ValueError("negative numbers are not allowed")
  269. n = as_int(n)
  270. if bits is None:
  271. bits = 0
  272. else:
  273. try:
  274. bits = as_int(bits)
  275. except ValueError:
  276. bits = -1
  277. else:
  278. if n.bit_length() > bits:
  279. raise ValueError(
  280. "`bits` must be >= {}".format(n.bit_length()))
  281. if not str:
  282. if bits >= 0:
  283. return [1 if i == "1" else 0 for i in bin(n)[2:].rjust(bits, "0")]
  284. else:
  285. return variations(range(2), n, repetition=True)
  286. else:
  287. if bits >= 0:
  288. return bin(n)[2:].rjust(bits, "0")
  289. else:
  290. return (bin(i)[2:].rjust(n, "0") for i in range(2**n))
  291. def variations(seq, n, repetition=False):
  292. r"""Returns an iterator over the n-sized variations of ``seq`` (size N).
  293. ``repetition`` controls whether items in ``seq`` can appear more than once;
  294. Examples
  295. ========
  296. ``variations(seq, n)`` will return `\frac{N!}{(N - n)!}` permutations without
  297. repetition of ``seq``'s elements:
  298. >>> from sympy import variations
  299. >>> list(variations([1, 2], 2))
  300. [(1, 2), (2, 1)]
  301. ``variations(seq, n, True)`` will return the `N^n` permutations obtained
  302. by allowing repetition of elements:
  303. >>> list(variations([1, 2], 2, repetition=True))
  304. [(1, 1), (1, 2), (2, 1), (2, 2)]
  305. If you ask for more items than are in the set you get the empty set unless
  306. you allow repetitions:
  307. >>> list(variations([0, 1], 3, repetition=False))
  308. []
  309. >>> list(variations([0, 1], 3, repetition=True))[:4]
  310. [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1)]
  311. .. seealso::
  312. `itertools.permutations
  313. <https://docs.python.org/3/library/itertools.html#itertools.permutations>`_,
  314. `itertools.product
  315. <https://docs.python.org/3/library/itertools.html#itertools.product>`_
  316. """
  317. if not repetition:
  318. seq = tuple(seq)
  319. if len(seq) < n:
  320. return iter(()) # 0 length iterator
  321. return permutations(seq, n)
  322. else:
  323. if n == 0:
  324. return iter(((),)) # yields 1 empty tuple
  325. else:
  326. return product(seq, repeat=n)
  327. def subsets(seq, k=None, repetition=False):
  328. r"""Generates all `k`-subsets (combinations) from an `n`-element set, ``seq``.
  329. A `k`-subset of an `n`-element set is any subset of length exactly `k`. The
  330. number of `k`-subsets of an `n`-element set is given by ``binomial(n, k)``,
  331. whereas there are `2^n` subsets all together. If `k` is ``None`` then all
  332. `2^n` subsets will be returned from shortest to longest.
  333. Examples
  334. ========
  335. >>> from sympy import subsets
  336. ``subsets(seq, k)`` will return the
  337. `\frac{n!}{k!(n - k)!}` `k`-subsets (combinations)
  338. without repetition, i.e. once an item has been removed, it can no
  339. longer be "taken":
  340. >>> list(subsets([1, 2], 2))
  341. [(1, 2)]
  342. >>> list(subsets([1, 2]))
  343. [(), (1,), (2,), (1, 2)]
  344. >>> list(subsets([1, 2, 3], 2))
  345. [(1, 2), (1, 3), (2, 3)]
  346. ``subsets(seq, k, repetition=True)`` will return the
  347. `\frac{(n - 1 + k)!}{k!(n - 1)!}`
  348. combinations *with* repetition:
  349. >>> list(subsets([1, 2], 2, repetition=True))
  350. [(1, 1), (1, 2), (2, 2)]
  351. If you ask for more items than are in the set you get the empty set unless
  352. you allow repetitions:
  353. >>> list(subsets([0, 1], 3, repetition=False))
  354. []
  355. >>> list(subsets([0, 1], 3, repetition=True))
  356. [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)]
  357. """
  358. if k is None:
  359. if not repetition:
  360. return chain.from_iterable((combinations(seq, k)
  361. for k in range(len(seq) + 1)))
  362. else:
  363. return chain.from_iterable((combinations_with_replacement(seq, k)
  364. for k in range(len(seq) + 1)))
  365. else:
  366. if not repetition:
  367. return combinations(seq, k)
  368. else:
  369. return combinations_with_replacement(seq, k)
  370. def filter_symbols(iterator, exclude):
  371. """
  372. Only yield elements from `iterator` that do not occur in `exclude`.
  373. Parameters
  374. ==========
  375. iterator : iterable
  376. iterator to take elements from
  377. exclude : iterable
  378. elements to exclude
  379. Returns
  380. =======
  381. iterator : iterator
  382. filtered iterator
  383. """
  384. exclude = set(exclude)
  385. for s in iterator:
  386. if s not in exclude:
  387. yield s
  388. def numbered_symbols(prefix='x', cls=None, start=0, exclude=(), *args, **assumptions):
  389. """
  390. Generate an infinite stream of Symbols consisting of a prefix and
  391. increasing subscripts provided that they do not occur in ``exclude``.
  392. Parameters
  393. ==========
  394. prefix : str, optional
  395. The prefix to use. By default, this function will generate symbols of
  396. the form "x0", "x1", etc.
  397. cls : class, optional
  398. The class to use. By default, it uses ``Symbol``, but you can also use ``Wild``
  399. or ``Dummy``.
  400. start : int, optional
  401. The start number. By default, it is 0.
  402. Returns
  403. =======
  404. sym : Symbol
  405. The subscripted symbols.
  406. """
  407. exclude = set(exclude or [])
  408. if cls is None:
  409. # We can't just make the default cls=Symbol because it isn't
  410. # imported yet.
  411. from sympy.core import Symbol
  412. cls = Symbol
  413. while True:
  414. name = '%s%s' % (prefix, start)
  415. s = cls(name, *args, **assumptions)
  416. if s not in exclude:
  417. yield s
  418. start += 1
  419. def capture(func):
  420. """Return the printed output of func().
  421. ``func`` should be a function without arguments that produces output with
  422. print statements.
  423. >>> from sympy.utilities.iterables import capture
  424. >>> from sympy import pprint
  425. >>> from sympy.abc import x
  426. >>> def foo():
  427. ... print('hello world!')
  428. ...
  429. >>> 'hello' in capture(foo) # foo, not foo()
  430. True
  431. >>> capture(lambda: pprint(2/x))
  432. '2\\n-\\nx\\n'
  433. """
  434. from io import StringIO
  435. import sys
  436. stdout = sys.stdout
  437. sys.stdout = file = StringIO()
  438. try:
  439. func()
  440. finally:
  441. sys.stdout = stdout
  442. return file.getvalue()
  443. def sift(seq, keyfunc, binary=False):
  444. """
  445. Sift the sequence, ``seq`` according to ``keyfunc``.
  446. Returns
  447. =======
  448. When ``binary`` is ``False`` (default), the output is a dictionary
  449. where elements of ``seq`` are stored in a list keyed to the value
  450. of keyfunc for that element. If ``binary`` is True then a tuple
  451. with lists ``T`` and ``F`` are returned where ``T`` is a list
  452. containing elements of seq for which ``keyfunc`` was ``True`` and
  453. ``F`` containing those elements for which ``keyfunc`` was ``False``;
  454. a ValueError is raised if the ``keyfunc`` is not binary.
  455. Examples
  456. ========
  457. >>> from sympy.utilities import sift
  458. >>> from sympy.abc import x, y
  459. >>> from sympy import sqrt, exp, pi, Tuple
  460. >>> sift(range(5), lambda x: x % 2)
  461. {0: [0, 2, 4], 1: [1, 3]}
  462. sift() returns a defaultdict() object, so any key that has no matches will
  463. give [].
  464. >>> sift([x], lambda x: x.is_commutative)
  465. {True: [x]}
  466. >>> _[False]
  467. []
  468. Sometimes you will not know how many keys you will get:
  469. >>> sift([sqrt(x), exp(x), (y**x)**2],
  470. ... lambda x: x.as_base_exp()[0])
  471. {E: [exp(x)], x: [sqrt(x)], y: [y**(2*x)]}
  472. Sometimes you expect the results to be binary; the
  473. results can be unpacked by setting ``binary`` to True:
  474. >>> sift(range(4), lambda x: x % 2, binary=True)
  475. ([1, 3], [0, 2])
  476. >>> sift(Tuple(1, pi), lambda x: x.is_rational, binary=True)
  477. ([1], [pi])
  478. A ValueError is raised if the predicate was not actually binary
  479. (which is a good test for the logic where sifting is used and
  480. binary results were expected):
  481. >>> unknown = exp(1) - pi # the rationality of this is unknown
  482. >>> args = Tuple(1, pi, unknown)
  483. >>> sift(args, lambda x: x.is_rational, binary=True)
  484. Traceback (most recent call last):
  485. ...
  486. ValueError: keyfunc gave non-binary output
  487. The non-binary sifting shows that there were 3 keys generated:
  488. >>> set(sift(args, lambda x: x.is_rational).keys())
  489. {None, False, True}
  490. If you need to sort the sifted items it might be better to use
  491. ``ordered`` which can economically apply multiple sort keys
  492. to a sequence while sorting.
  493. See Also
  494. ========
  495. ordered
  496. """
  497. if not binary:
  498. m = defaultdict(list)
  499. for i in seq:
  500. m[keyfunc(i)].append(i)
  501. return m
  502. sift = F, T = [], []
  503. for i in seq:
  504. try:
  505. sift[keyfunc(i)].append(i)
  506. except (IndexError, TypeError):
  507. raise ValueError('keyfunc gave non-binary output')
  508. return T, F
  509. def take(iter, n):
  510. """Return ``n`` items from ``iter`` iterator. """
  511. return [ value for _, value in zip(range(n), iter) ]
  512. def dict_merge(*dicts):
  513. """Merge dictionaries into a single dictionary. """
  514. merged = {}
  515. for dict in dicts:
  516. merged.update(dict)
  517. return merged
  518. def common_prefix(*seqs):
  519. """Return the subsequence that is a common start of sequences in ``seqs``.
  520. >>> from sympy.utilities.iterables import common_prefix
  521. >>> common_prefix(list(range(3)))
  522. [0, 1, 2]
  523. >>> common_prefix(list(range(3)), list(range(4)))
  524. [0, 1, 2]
  525. >>> common_prefix([1, 2, 3], [1, 2, 5])
  526. [1, 2]
  527. >>> common_prefix([1, 2, 3], [1, 3, 5])
  528. [1]
  529. """
  530. if not all(seqs):
  531. return []
  532. elif len(seqs) == 1:
  533. return seqs[0]
  534. i = 0
  535. for i in range(min(len(s) for s in seqs)):
  536. if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))):
  537. break
  538. else:
  539. i += 1
  540. return seqs[0][:i]
  541. def common_suffix(*seqs):
  542. """Return the subsequence that is a common ending of sequences in ``seqs``.
  543. >>> from sympy.utilities.iterables import common_suffix
  544. >>> common_suffix(list(range(3)))
  545. [0, 1, 2]
  546. >>> common_suffix(list(range(3)), list(range(4)))
  547. []
  548. >>> common_suffix([1, 2, 3], [9, 2, 3])
  549. [2, 3]
  550. >>> common_suffix([1, 2, 3], [9, 7, 3])
  551. [3]
  552. """
  553. if not all(seqs):
  554. return []
  555. elif len(seqs) == 1:
  556. return seqs[0]
  557. i = 0
  558. for i in range(-1, -min(len(s) for s in seqs) - 1, -1):
  559. if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))):
  560. break
  561. else:
  562. i -= 1
  563. if i == -1:
  564. return []
  565. else:
  566. return seqs[0][i + 1:]
  567. def prefixes(seq):
  568. """
  569. Generate all prefixes of a sequence.
  570. Examples
  571. ========
  572. >>> from sympy.utilities.iterables import prefixes
  573. >>> list(prefixes([1,2,3,4]))
  574. [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
  575. """
  576. n = len(seq)
  577. for i in range(n):
  578. yield seq[:i + 1]
  579. def postfixes(seq):
  580. """
  581. Generate all postfixes of a sequence.
  582. Examples
  583. ========
  584. >>> from sympy.utilities.iterables import postfixes
  585. >>> list(postfixes([1,2,3,4]))
  586. [[4], [3, 4], [2, 3, 4], [1, 2, 3, 4]]
  587. """
  588. n = len(seq)
  589. for i in range(n):
  590. yield seq[n - i - 1:]
  591. def topological_sort(graph, key=None):
  592. r"""
  593. Topological sort of graph's vertices.
  594. Parameters
  595. ==========
  596. graph : tuple[list, list[tuple[T, T]]
  597. A tuple consisting of a list of vertices and a list of edges of
  598. a graph to be sorted topologically.
  599. key : callable[T] (optional)
  600. Ordering key for vertices on the same level. By default the natural
  601. (e.g. lexicographic) ordering is used (in this case the base type
  602. must implement ordering relations).
  603. Examples
  604. ========
  605. Consider a graph::
  606. +---+ +---+ +---+
  607. | 7 |\ | 5 | | 3 |
  608. +---+ \ +---+ +---+
  609. | _\___/ ____ _/ |
  610. | / \___/ \ / |
  611. V V V V |
  612. +----+ +---+ |
  613. | 11 | | 8 | |
  614. +----+ +---+ |
  615. | | \____ ___/ _ |
  616. | \ \ / / \ |
  617. V \ V V / V V
  618. +---+ \ +---+ | +----+
  619. | 2 | | | 9 | | | 10 |
  620. +---+ | +---+ | +----+
  621. \________/
  622. where vertices are integers. This graph can be encoded using
  623. elementary Python's data structures as follows::
  624. >>> V = [2, 3, 5, 7, 8, 9, 10, 11]
  625. >>> E = [(7, 11), (7, 8), (5, 11), (3, 8), (3, 10),
  626. ... (11, 2), (11, 9), (11, 10), (8, 9)]
  627. To compute a topological sort for graph ``(V, E)`` issue::
  628. >>> from sympy.utilities.iterables import topological_sort
  629. >>> topological_sort((V, E))
  630. [3, 5, 7, 8, 11, 2, 9, 10]
  631. If specific tie breaking approach is needed, use ``key`` parameter::
  632. >>> topological_sort((V, E), key=lambda v: -v)
  633. [7, 5, 11, 3, 10, 8, 9, 2]
  634. Only acyclic graphs can be sorted. If the input graph has a cycle,
  635. then ``ValueError`` will be raised::
  636. >>> topological_sort((V, E + [(10, 7)]))
  637. Traceback (most recent call last):
  638. ...
  639. ValueError: cycle detected
  640. References
  641. ==========
  642. .. [1] https://en.wikipedia.org/wiki/Topological_sorting
  643. """
  644. V, E = graph
  645. L = []
  646. S = set(V)
  647. E = list(E)
  648. for v, u in E:
  649. S.discard(u)
  650. if key is None:
  651. def key(value):
  652. return value
  653. S = sorted(S, key=key, reverse=True)
  654. while S:
  655. node = S.pop()
  656. L.append(node)
  657. for u, v in list(E):
  658. if u == node:
  659. E.remove((u, v))
  660. for _u, _v in E:
  661. if v == _v:
  662. break
  663. else:
  664. kv = key(v)
  665. for i, s in enumerate(S):
  666. ks = key(s)
  667. if kv > ks:
  668. S.insert(i, v)
  669. break
  670. else:
  671. S.append(v)
  672. if E:
  673. raise ValueError("cycle detected")
  674. else:
  675. return L
  676. def strongly_connected_components(G):
  677. r"""
  678. Strongly connected components of a directed graph in reverse topological
  679. order.
  680. Parameters
  681. ==========
  682. graph : tuple[list, list[tuple[T, T]]
  683. A tuple consisting of a list of vertices and a list of edges of
  684. a graph whose strongly connected components are to be found.
  685. Examples
  686. ========
  687. Consider a directed graph (in dot notation)::
  688. digraph {
  689. A -> B
  690. A -> C
  691. B -> C
  692. C -> B
  693. B -> D
  694. }
  695. .. graphviz::
  696. digraph {
  697. A -> B
  698. A -> C
  699. B -> C
  700. C -> B
  701. B -> D
  702. }
  703. where vertices are the letters A, B, C and D. This graph can be encoded
  704. using Python's elementary data structures as follows::
  705. >>> V = ['A', 'B', 'C', 'D']
  706. >>> E = [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'B'), ('B', 'D')]
  707. The strongly connected components of this graph can be computed as
  708. >>> from sympy.utilities.iterables import strongly_connected_components
  709. >>> strongly_connected_components((V, E))
  710. [['D'], ['B', 'C'], ['A']]
  711. This also gives the components in reverse topological order.
  712. Since the subgraph containing B and C has a cycle they must be together in
  713. a strongly connected component. A and D are connected to the rest of the
  714. graph but not in a cyclic manner so they appear as their own strongly
  715. connected components.
  716. Notes
  717. =====
  718. The vertices of the graph must be hashable for the data structures used.
  719. If the vertices are unhashable replace them with integer indices.
  720. This function uses Tarjan's algorithm to compute the strongly connected
  721. components in `O(|V|+|E|)` (linear) time.
  722. References
  723. ==========
  724. .. [1] https://en.wikipedia.org/wiki/Strongly_connected_component
  725. .. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
  726. See Also
  727. ========
  728. sympy.utilities.iterables.connected_components
  729. """
  730. # Map from a vertex to its neighbours
  731. V, E = G
  732. Gmap = {vi: [] for vi in V}
  733. for v1, v2 in E:
  734. Gmap[v1].append(v2)
  735. return _strongly_connected_components(V, Gmap)
  736. def _strongly_connected_components(V, Gmap):
  737. """More efficient internal routine for strongly_connected_components"""
  738. #
  739. # Here V is an iterable of vertices and Gmap is a dict mapping each vertex
  740. # to a list of neighbours e.g.:
  741. #
  742. # V = [0, 1, 2, 3]
  743. # Gmap = {0: [2, 3], 1: [0]}
  744. #
  745. # For a large graph these data structures can often be created more
  746. # efficiently then those expected by strongly_connected_components() which
  747. # in this case would be
  748. #
  749. # V = [0, 1, 2, 3]
  750. # Gmap = [(0, 2), (0, 3), (1, 0)]
  751. #
  752. # XXX: Maybe this should be the recommended function to use instead...
  753. #
  754. # Non-recursive Tarjan's algorithm:
  755. lowlink = {}
  756. indices = {}
  757. stack = OrderedDict()
  758. callstack = []
  759. components = []
  760. nomore = object()
  761. def start(v):
  762. index = len(stack)
  763. indices[v] = lowlink[v] = index
  764. stack[v] = None
  765. callstack.append((v, iter(Gmap[v])))
  766. def finish(v1):
  767. # Finished a component?
  768. if lowlink[v1] == indices[v1]:
  769. component = [stack.popitem()[0]]
  770. while component[-1] is not v1:
  771. component.append(stack.popitem()[0])
  772. components.append(component[::-1])
  773. v2, _ = callstack.pop()
  774. if callstack:
  775. v1, _ = callstack[-1]
  776. lowlink[v1] = min(lowlink[v1], lowlink[v2])
  777. for v in V:
  778. if v in indices:
  779. continue
  780. start(v)
  781. while callstack:
  782. v1, it1 = callstack[-1]
  783. v2 = next(it1, nomore)
  784. # Finished children of v1?
  785. if v2 is nomore:
  786. finish(v1)
  787. # Recurse on v2
  788. elif v2 not in indices:
  789. start(v2)
  790. elif v2 in stack:
  791. lowlink[v1] = min(lowlink[v1], indices[v2])
  792. # Reverse topological sort order:
  793. return components
  794. def connected_components(G):
  795. r"""
  796. Connected components of an undirected graph or weakly connected components
  797. of a directed graph.
  798. Parameters
  799. ==========
  800. graph : tuple[list, list[tuple[T, T]]
  801. A tuple consisting of a list of vertices and a list of edges of
  802. a graph whose connected components are to be found.
  803. Examples
  804. ========
  805. Given an undirected graph::
  806. graph {
  807. A -- B
  808. C -- D
  809. }
  810. .. graphviz::
  811. graph {
  812. A -- B
  813. C -- D
  814. }
  815. We can find the connected components using this function if we include
  816. each edge in both directions::
  817. >>> from sympy.utilities.iterables import connected_components
  818. >>> V = ['A', 'B', 'C', 'D']
  819. >>> E = [('A', 'B'), ('B', 'A'), ('C', 'D'), ('D', 'C')]
  820. >>> connected_components((V, E))
  821. [['A', 'B'], ['C', 'D']]
  822. The weakly connected components of a directed graph can found the same
  823. way.
  824. Notes
  825. =====
  826. The vertices of the graph must be hashable for the data structures used.
  827. If the vertices are unhashable replace them with integer indices.
  828. This function uses Tarjan's algorithm to compute the connected components
  829. in `O(|V|+|E|)` (linear) time.
  830. References
  831. ==========
  832. .. [1] https://en.wikipedia.org/wiki/Component_%28graph_theory%29
  833. .. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
  834. See Also
  835. ========
  836. sympy.utilities.iterables.strongly_connected_components
  837. """
  838. # Duplicate edges both ways so that the graph is effectively undirected
  839. # and return the strongly connected components:
  840. V, E = G
  841. E_undirected = []
  842. for v1, v2 in E:
  843. E_undirected.extend([(v1, v2), (v2, v1)])
  844. return strongly_connected_components((V, E_undirected))
  845. def rotate_left(x, y):
  846. """
  847. Left rotates a list x by the number of steps specified
  848. in y.
  849. Examples
  850. ========
  851. >>> from sympy.utilities.iterables import rotate_left
  852. >>> a = [0, 1, 2]
  853. >>> rotate_left(a, 1)
  854. [1, 2, 0]
  855. """
  856. if len(x) == 0:
  857. return []
  858. y = y % len(x)
  859. return x[y:] + x[:y]
  860. def rotate_right(x, y):
  861. """
  862. Right rotates a list x by the number of steps specified
  863. in y.
  864. Examples
  865. ========
  866. >>> from sympy.utilities.iterables import rotate_right
  867. >>> a = [0, 1, 2]
  868. >>> rotate_right(a, 1)
  869. [2, 0, 1]
  870. """
  871. if len(x) == 0:
  872. return []
  873. y = len(x) - y % len(x)
  874. return x[y:] + x[:y]
  875. def least_rotation(x, key=None):
  876. '''
  877. Returns the number of steps of left rotation required to
  878. obtain lexicographically minimal string/list/tuple, etc.
  879. Examples
  880. ========
  881. >>> from sympy.utilities.iterables import least_rotation, rotate_left
  882. >>> a = [3, 1, 5, 1, 2]
  883. >>> least_rotation(a)
  884. 3
  885. >>> rotate_left(a, _)
  886. [1, 2, 3, 1, 5]
  887. References
  888. ==========
  889. .. [1] https://en.wikipedia.org/wiki/Lexicographically_minimal_string_rotation
  890. '''
  891. from sympy.functions.elementary.miscellaneous import Id
  892. if key is None: key = Id
  893. S = x + x # Concatenate string to it self to avoid modular arithmetic
  894. f = [-1] * len(S) # Failure function
  895. k = 0 # Least rotation of string found so far
  896. for j in range(1,len(S)):
  897. sj = S[j]
  898. i = f[j-k-1]
  899. while i != -1 and sj != S[k+i+1]:
  900. if key(sj) < key(S[k+i+1]):
  901. k = j-i-1
  902. i = f[i]
  903. if sj != S[k+i+1]:
  904. if key(sj) < key(S[k]):
  905. k = j
  906. f[j-k] = -1
  907. else:
  908. f[j-k] = i+1
  909. return k
  910. def multiset_combinations(m, n, g=None):
  911. """
  912. Return the unique combinations of size ``n`` from multiset ``m``.
  913. Examples
  914. ========
  915. >>> from sympy.utilities.iterables import multiset_combinations
  916. >>> from itertools import combinations
  917. >>> [''.join(i) for i in multiset_combinations('baby', 3)]
  918. ['abb', 'aby', 'bby']
  919. >>> def count(f, s): return len(list(f(s, 3)))
  920. The number of combinations depends on the number of letters; the
  921. number of unique combinations depends on how the letters are
  922. repeated.
  923. >>> s1 = 'abracadabra'
  924. >>> s2 = 'banana tree'
  925. >>> count(combinations, s1), count(multiset_combinations, s1)
  926. (165, 23)
  927. >>> count(combinations, s2), count(multiset_combinations, s2)
  928. (165, 54)
  929. """
  930. from sympy.core.sorting import ordered
  931. if g is None:
  932. if isinstance(m, dict):
  933. if any(as_int(v) < 0 for v in m.values()):
  934. raise ValueError('counts cannot be negative')
  935. N = sum(m.values())
  936. if n > N:
  937. return
  938. g = [[k, m[k]] for k in ordered(m)]
  939. else:
  940. m = list(m)
  941. N = len(m)
  942. if n > N:
  943. return
  944. try:
  945. m = multiset(m)
  946. g = [(k, m[k]) for k in ordered(m)]
  947. except TypeError:
  948. m = list(ordered(m))
  949. g = [list(i) for i in group(m, multiple=False)]
  950. del m
  951. else:
  952. # not checking counts since g is intended for internal use
  953. N = sum(v for k, v in g)
  954. if n > N or not n:
  955. yield []
  956. else:
  957. for i, (k, v) in enumerate(g):
  958. if v >= n:
  959. yield [k]*n
  960. v = n - 1
  961. for v in range(min(n, v), 0, -1):
  962. for j in multiset_combinations(None, n - v, g[i + 1:]):
  963. rv = [k]*v + j
  964. if len(rv) == n:
  965. yield rv
  966. def multiset_permutations(m, size=None, g=None):
  967. """
  968. Return the unique permutations of multiset ``m``.
  969. Examples
  970. ========
  971. >>> from sympy.utilities.iterables import multiset_permutations
  972. >>> from sympy import factorial
  973. >>> [''.join(i) for i in multiset_permutations('aab')]
  974. ['aab', 'aba', 'baa']
  975. >>> factorial(len('banana'))
  976. 720
  977. >>> len(list(multiset_permutations('banana')))
  978. 60
  979. """
  980. from sympy.core.sorting import ordered
  981. if g is None:
  982. if isinstance(m, dict):
  983. if any(as_int(v) < 0 for v in m.values()):
  984. raise ValueError('counts cannot be negative')
  985. g = [[k, m[k]] for k in ordered(m)]
  986. else:
  987. m = list(ordered(m))
  988. g = [list(i) for i in group(m, multiple=False)]
  989. del m
  990. do = [gi for gi in g if gi[1] > 0]
  991. SUM = sum([gi[1] for gi in do])
  992. if not do or size is not None and (size > SUM or size < 1):
  993. if not do and size is None or size == 0:
  994. yield []
  995. return
  996. elif size == 1:
  997. for k, v in do:
  998. yield [k]
  999. elif len(do) == 1:
  1000. k, v = do[0]
  1001. v = v if size is None else (size if size <= v else 0)
  1002. yield [k for i in range(v)]
  1003. elif all(v == 1 for k, v in do):
  1004. for p in permutations([k for k, v in do], size):
  1005. yield list(p)
  1006. else:
  1007. size = size if size is not None else SUM
  1008. for i, (k, v) in enumerate(do):
  1009. do[i][1] -= 1
  1010. for j in multiset_permutations(None, size - 1, do):
  1011. if j:
  1012. yield [k] + j
  1013. do[i][1] += 1
  1014. def _partition(seq, vector, m=None):
  1015. """
  1016. Return the partition of seq as specified by the partition vector.
  1017. Examples
  1018. ========
  1019. >>> from sympy.utilities.iterables import _partition
  1020. >>> _partition('abcde', [1, 0, 1, 2, 0])
  1021. [['b', 'e'], ['a', 'c'], ['d']]
  1022. Specifying the number of bins in the partition is optional:
  1023. >>> _partition('abcde', [1, 0, 1, 2, 0], 3)
  1024. [['b', 'e'], ['a', 'c'], ['d']]
  1025. The output of _set_partitions can be passed as follows:
  1026. >>> output = (3, [1, 0, 1, 2, 0])
  1027. >>> _partition('abcde', *output)
  1028. [['b', 'e'], ['a', 'c'], ['d']]
  1029. See Also
  1030. ========
  1031. combinatorics.partitions.Partition.from_rgs
  1032. """
  1033. if m is None:
  1034. m = max(vector) + 1
  1035. elif isinstance(vector, int): # entered as m, vector
  1036. vector, m = m, vector
  1037. p = [[] for i in range(m)]
  1038. for i, v in enumerate(vector):
  1039. p[v].append(seq[i])
  1040. return p
  1041. def _set_partitions(n):
  1042. """Cycle through all partitions of n elements, yielding the
  1043. current number of partitions, ``m``, and a mutable list, ``q``
  1044. such that ``element[i]`` is in part ``q[i]`` of the partition.
  1045. NOTE: ``q`` is modified in place and generally should not be changed
  1046. between function calls.
  1047. Examples
  1048. ========
  1049. >>> from sympy.utilities.iterables import _set_partitions, _partition
  1050. >>> for m, q in _set_partitions(3):
  1051. ... print('%s %s %s' % (m, q, _partition('abc', q, m)))
  1052. 1 [0, 0, 0] [['a', 'b', 'c']]
  1053. 2 [0, 0, 1] [['a', 'b'], ['c']]
  1054. 2 [0, 1, 0] [['a', 'c'], ['b']]
  1055. 2 [0, 1, 1] [['a'], ['b', 'c']]
  1056. 3 [0, 1, 2] [['a'], ['b'], ['c']]
  1057. Notes
  1058. =====
  1059. This algorithm is similar to, and solves the same problem as,
  1060. Algorithm 7.2.1.5H, from volume 4A of Knuth's The Art of Computer
  1061. Programming. Knuth uses the term "restricted growth string" where
  1062. this code refers to a "partition vector". In each case, the meaning is
  1063. the same: the value in the ith element of the vector specifies to
  1064. which part the ith set element is to be assigned.
  1065. At the lowest level, this code implements an n-digit big-endian
  1066. counter (stored in the array q) which is incremented (with carries) to
  1067. get the next partition in the sequence. A special twist is that a
  1068. digit is constrained to be at most one greater than the maximum of all
  1069. the digits to the left of it. The array p maintains this maximum, so
  1070. that the code can efficiently decide when a digit can be incremented
  1071. in place or whether it needs to be reset to 0 and trigger a carry to
  1072. the next digit. The enumeration starts with all the digits 0 (which
  1073. corresponds to all the set elements being assigned to the same 0th
  1074. part), and ends with 0123...n, which corresponds to each set element
  1075. being assigned to a different, singleton, part.
  1076. This routine was rewritten to use 0-based lists while trying to
  1077. preserve the beauty and efficiency of the original algorithm.
  1078. References
  1079. ==========
  1080. .. [1] Nijenhuis, Albert and Wilf, Herbert. (1978) Combinatorial Algorithms,
  1081. 2nd Ed, p 91, algorithm "nexequ". Available online from
  1082. https://www.math.upenn.edu/~wilf/website/CombAlgDownld.html (viewed
  1083. November 17, 2012).
  1084. """
  1085. p = [0]*n
  1086. q = [0]*n
  1087. nc = 1
  1088. yield nc, q
  1089. while nc != n:
  1090. m = n
  1091. while 1:
  1092. m -= 1
  1093. i = q[m]
  1094. if p[i] != 1:
  1095. break
  1096. q[m] = 0
  1097. i += 1
  1098. q[m] = i
  1099. m += 1
  1100. nc += m - n
  1101. p[0] += n - m
  1102. if i == nc:
  1103. p[nc] = 0
  1104. nc += 1
  1105. p[i - 1] -= 1
  1106. p[i] += 1
  1107. yield nc, q
  1108. def multiset_partitions(multiset, m=None):
  1109. """
  1110. Return unique partitions of the given multiset (in list form).
  1111. If ``m`` is None, all multisets will be returned, otherwise only
  1112. partitions with ``m`` parts will be returned.
  1113. If ``multiset`` is an integer, a range [0, 1, ..., multiset - 1]
  1114. will be supplied.
  1115. Examples
  1116. ========
  1117. >>> from sympy.utilities.iterables import multiset_partitions
  1118. >>> list(multiset_partitions([1, 2, 3, 4], 2))
  1119. [[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]],
  1120. [[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]],
  1121. [[1], [2, 3, 4]]]
  1122. >>> list(multiset_partitions([1, 2, 3, 4], 1))
  1123. [[[1, 2, 3, 4]]]
  1124. Only unique partitions are returned and these will be returned in a
  1125. canonical order regardless of the order of the input:
  1126. >>> a = [1, 2, 2, 1]
  1127. >>> ans = list(multiset_partitions(a, 2))
  1128. >>> a.sort()
  1129. >>> list(multiset_partitions(a, 2)) == ans
  1130. True
  1131. >>> a = range(3, 1, -1)
  1132. >>> (list(multiset_partitions(a)) ==
  1133. ... list(multiset_partitions(sorted(a))))
  1134. True
  1135. If m is omitted then all partitions will be returned:
  1136. >>> list(multiset_partitions([1, 1, 2]))
  1137. [[[1, 1, 2]], [[1, 1], [2]], [[1, 2], [1]], [[1], [1], [2]]]
  1138. >>> list(multiset_partitions([1]*3))
  1139. [[[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]]
  1140. Counting
  1141. ========
  1142. The number of partitions of a set is given by the bell number:
  1143. >>> from sympy import bell
  1144. >>> len(list(multiset_partitions(5))) == bell(5) == 52
  1145. True
  1146. The number of partitions of length k from a set of size n is given by the
  1147. Stirling Number of the 2nd kind:
  1148. >>> from sympy.functions.combinatorial.numbers import stirling
  1149. >>> stirling(5, 2) == len(list(multiset_partitions(5, 2))) == 15
  1150. True
  1151. These comments on counting apply to *sets*, not multisets.
  1152. Notes
  1153. =====
  1154. When all the elements are the same in the multiset, the order
  1155. of the returned partitions is determined by the ``partitions``
  1156. routine. If one is counting partitions then it is better to use
  1157. the ``nT`` function.
  1158. See Also
  1159. ========
  1160. partitions
  1161. sympy.combinatorics.partitions.Partition
  1162. sympy.combinatorics.partitions.IntegerPartition
  1163. sympy.functions.combinatorial.numbers.nT
  1164. """
  1165. # This function looks at the supplied input and dispatches to
  1166. # several special-case routines as they apply.
  1167. if isinstance(multiset, int):
  1168. n = multiset
  1169. if m and m > n:
  1170. return
  1171. multiset = list(range(n))
  1172. if m == 1:
  1173. yield [multiset[:]]
  1174. return
  1175. # If m is not None, it can sometimes be faster to use
  1176. # MultisetPartitionTraverser.enum_range() even for inputs
  1177. # which are sets. Since the _set_partitions code is quite
  1178. # fast, this is only advantageous when the overall set
  1179. # partitions outnumber those with the desired number of parts
  1180. # by a large factor. (At least 60.) Such a switch is not
  1181. # currently implemented.
  1182. for nc, q in _set_partitions(n):
  1183. if m is None or nc == m:
  1184. rv = [[] for i in range(nc)]
  1185. for i in range(n):
  1186. rv[q[i]].append(multiset[i])
  1187. yield rv
  1188. return
  1189. if len(multiset) == 1 and isinstance(multiset, str):
  1190. multiset = [multiset]
  1191. if not has_variety(multiset):
  1192. # Only one component, repeated n times. The resulting
  1193. # partitions correspond to partitions of integer n.
  1194. n = len(multiset)
  1195. if m and m > n:
  1196. return
  1197. if m == 1:
  1198. yield [multiset[:]]
  1199. return
  1200. x = multiset[:1]
  1201. for size, p in partitions(n, m, size=True):
  1202. if m is None or size == m:
  1203. rv = []
  1204. for k in sorted(p):
  1205. rv.extend([x*k]*p[k])
  1206. yield rv
  1207. else:
  1208. from sympy.core.sorting import ordered
  1209. multiset = list(ordered(multiset))
  1210. n = len(multiset)
  1211. if m and m > n:
  1212. return
  1213. if m == 1:
  1214. yield [multiset[:]]
  1215. return
  1216. # Split the information of the multiset into two lists -
  1217. # one of the elements themselves, and one (of the same length)
  1218. # giving the number of repeats for the corresponding element.
  1219. elements, multiplicities = zip(*group(multiset, False))
  1220. if len(elements) < len(multiset):
  1221. # General case - multiset with more than one distinct element
  1222. # and at least one element repeated more than once.
  1223. if m:
  1224. mpt = MultisetPartitionTraverser()
  1225. for state in mpt.enum_range(multiplicities, m-1, m):
  1226. yield list_visitor(state, elements)
  1227. else:
  1228. for state in multiset_partitions_taocp(multiplicities):
  1229. yield list_visitor(state, elements)
  1230. else:
  1231. # Set partitions case - no repeated elements. Pretty much
  1232. # same as int argument case above, with same possible, but
  1233. # currently unimplemented optimization for some cases when
  1234. # m is not None
  1235. for nc, q in _set_partitions(n):
  1236. if m is None or nc == m:
  1237. rv = [[] for i in range(nc)]
  1238. for i in range(n):
  1239. rv[q[i]].append(i)
  1240. yield [[multiset[j] for j in i] for i in rv]
  1241. def partitions(n, m=None, k=None, size=False):
  1242. """Generate all partitions of positive integer, n.
  1243. Parameters
  1244. ==========
  1245. m : integer (default gives partitions of all sizes)
  1246. limits number of parts in partition (mnemonic: m, maximum parts)
  1247. k : integer (default gives partitions number from 1 through n)
  1248. limits the numbers that are kept in the partition (mnemonic: k, keys)
  1249. size : bool (default False, only partition is returned)
  1250. when ``True`` then (M, P) is returned where M is the sum of the
  1251. multiplicities and P is the generated partition.
  1252. Each partition is represented as a dictionary, mapping an integer
  1253. to the number of copies of that integer in the partition. For example,
  1254. the first partition of 4 returned is {4: 1}, "4: one of them".
  1255. Examples
  1256. ========
  1257. >>> from sympy.utilities.iterables import partitions
  1258. The numbers appearing in the partition (the key of the returned dict)
  1259. are limited with k:
  1260. >>> for p in partitions(6, k=2): # doctest: +SKIP
  1261. ... print(p)
  1262. {2: 3}
  1263. {1: 2, 2: 2}
  1264. {1: 4, 2: 1}
  1265. {1: 6}
  1266. The maximum number of parts in the partition (the sum of the values in
  1267. the returned dict) are limited with m (default value, None, gives
  1268. partitions from 1 through n):
  1269. >>> for p in partitions(6, m=2): # doctest: +SKIP
  1270. ... print(p)
  1271. ...
  1272. {6: 1}
  1273. {1: 1, 5: 1}
  1274. {2: 1, 4: 1}
  1275. {3: 2}
  1276. References
  1277. ==========
  1278. .. [1] modified from Tim Peter's version to allow for k and m values:
  1279. https://code.activestate.com/recipes/218332-generator-for-integer-partitions/
  1280. See Also
  1281. ========
  1282. sympy.combinatorics.partitions.Partition
  1283. sympy.combinatorics.partitions.IntegerPartition
  1284. """
  1285. if (n <= 0 or
  1286. m is not None and m < 1 or
  1287. k is not None and k < 1 or
  1288. m and k and m*k < n):
  1289. # the empty set is the only way to handle these inputs
  1290. # and returning {} to represent it is consistent with
  1291. # the counting convention, e.g. nT(0) == 1.
  1292. if size:
  1293. yield 0, {}
  1294. else:
  1295. yield {}
  1296. return
  1297. if m is None:
  1298. m = n
  1299. else:
  1300. m = min(m, n)
  1301. k = min(k or n, n)
  1302. n, m, k = as_int(n), as_int(m), as_int(k)
  1303. q, r = divmod(n, k)
  1304. ms = {k: q}
  1305. keys = [k] # ms.keys(), from largest to smallest
  1306. if r:
  1307. ms[r] = 1
  1308. keys.append(r)
  1309. room = m - q - bool(r)
  1310. if size:
  1311. yield sum(ms.values()), ms.copy()
  1312. else:
  1313. yield ms.copy()
  1314. while keys != [1]:
  1315. # Reuse any 1's.
  1316. if keys[-1] == 1:
  1317. del keys[-1]
  1318. reuse = ms.pop(1)
  1319. room += reuse
  1320. else:
  1321. reuse = 0
  1322. while 1:
  1323. # Let i be the smallest key larger than 1. Reuse one
  1324. # instance of i.
  1325. i = keys[-1]
  1326. newcount = ms[i] = ms[i] - 1
  1327. reuse += i
  1328. if newcount == 0:
  1329. del keys[-1], ms[i]
  1330. room += 1
  1331. # Break the remainder into pieces of size i-1.
  1332. i -= 1
  1333. q, r = divmod(reuse, i)
  1334. need = q + bool(r)
  1335. if need > room:
  1336. if not keys:
  1337. return
  1338. continue
  1339. ms[i] = q
  1340. keys.append(i)
  1341. if r:
  1342. ms[r] = 1
  1343. keys.append(r)
  1344. break
  1345. room -= need
  1346. if size:
  1347. yield sum(ms.values()), ms.copy()
  1348. else:
  1349. yield ms.copy()
  1350. def ordered_partitions(n, m=None, sort=True):
  1351. """Generates ordered partitions of integer ``n``.
  1352. Parameters
  1353. ==========
  1354. m : integer (default None)
  1355. The default value gives partitions of all sizes else only
  1356. those with size m. In addition, if ``m`` is not None then
  1357. partitions are generated *in place* (see examples).
  1358. sort : bool (default True)
  1359. Controls whether partitions are
  1360. returned in sorted order when ``m`` is not None; when False,
  1361. the partitions are returned as fast as possible with elements
  1362. sorted, but when m|n the partitions will not be in
  1363. ascending lexicographical order.
  1364. Examples
  1365. ========
  1366. >>> from sympy.utilities.iterables import ordered_partitions
  1367. All partitions of 5 in ascending lexicographical:
  1368. >>> for p in ordered_partitions(5):
  1369. ... print(p)
  1370. [1, 1, 1, 1, 1]
  1371. [1, 1, 1, 2]
  1372. [1, 1, 3]
  1373. [1, 2, 2]
  1374. [1, 4]
  1375. [2, 3]
  1376. [5]
  1377. Only partitions of 5 with two parts:
  1378. >>> for p in ordered_partitions(5, 2):
  1379. ... print(p)
  1380. [1, 4]
  1381. [2, 3]
  1382. When ``m`` is given, a given list objects will be used more than
  1383. once for speed reasons so you will not see the correct partitions
  1384. unless you make a copy of each as it is generated:
  1385. >>> [p for p in ordered_partitions(7, 3)]
  1386. [[1, 1, 1], [1, 1, 1], [1, 1, 1], [2, 2, 2]]
  1387. >>> [list(p) for p in ordered_partitions(7, 3)]
  1388. [[1, 1, 5], [1, 2, 4], [1, 3, 3], [2, 2, 3]]
  1389. When ``n`` is a multiple of ``m``, the elements are still sorted
  1390. but the partitions themselves will be *unordered* if sort is False;
  1391. the default is to return them in ascending lexicographical order.
  1392. >>> for p in ordered_partitions(6, 2):
  1393. ... print(p)
  1394. [1, 5]
  1395. [2, 4]
  1396. [3, 3]
  1397. But if speed is more important than ordering, sort can be set to
  1398. False:
  1399. >>> for p in ordered_partitions(6, 2, sort=False):
  1400. ... print(p)
  1401. [1, 5]
  1402. [3, 3]
  1403. [2, 4]
  1404. References
  1405. ==========
  1406. .. [1] Generating Integer Partitions, [online],
  1407. Available: https://jeromekelleher.net/generating-integer-partitions.html
  1408. .. [2] Jerome Kelleher and Barry O'Sullivan, "Generating All
  1409. Partitions: A Comparison Of Two Encodings", [online],
  1410. Available: https://arxiv.org/pdf/0909.2331v2.pdf
  1411. """
  1412. if n < 1 or m is not None and m < 1:
  1413. # the empty set is the only way to handle these inputs
  1414. # and returning {} to represent it is consistent with
  1415. # the counting convention, e.g. nT(0) == 1.
  1416. yield []
  1417. return
  1418. if m is None:
  1419. # The list `a`'s leading elements contain the partition in which
  1420. # y is the biggest element and x is either the same as y or the
  1421. # 2nd largest element; v and w are adjacent element indices
  1422. # to which x and y are being assigned, respectively.
  1423. a = [1]*n
  1424. y = -1
  1425. v = n
  1426. while v > 0:
  1427. v -= 1
  1428. x = a[v] + 1
  1429. while y >= 2 * x:
  1430. a[v] = x
  1431. y -= x
  1432. v += 1
  1433. w = v + 1
  1434. while x <= y:
  1435. a[v] = x
  1436. a[w] = y
  1437. yield a[:w + 1]
  1438. x += 1
  1439. y -= 1
  1440. a[v] = x + y
  1441. y = a[v] - 1
  1442. yield a[:w]
  1443. elif m == 1:
  1444. yield [n]
  1445. elif n == m:
  1446. yield [1]*n
  1447. else:
  1448. # recursively generate partitions of size m
  1449. for b in range(1, n//m + 1):
  1450. a = [b]*m
  1451. x = n - b*m
  1452. if not x:
  1453. if sort:
  1454. yield a
  1455. elif not sort and x <= m:
  1456. for ax in ordered_partitions(x, sort=False):
  1457. mi = len(ax)
  1458. a[-mi:] = [i + b for i in ax]
  1459. yield a
  1460. a[-mi:] = [b]*mi
  1461. else:
  1462. for mi in range(1, m):
  1463. for ax in ordered_partitions(x, mi, sort=True):
  1464. a[-mi:] = [i + b for i in ax]
  1465. yield a
  1466. a[-mi:] = [b]*mi
  1467. def binary_partitions(n):
  1468. """
  1469. Generates the binary partition of n.
  1470. A binary partition consists only of numbers that are
  1471. powers of two. Each step reduces a `2^{k+1}` to `2^k` and
  1472. `2^k`. Thus 16 is converted to 8 and 8.
  1473. Examples
  1474. ========
  1475. >>> from sympy.utilities.iterables import binary_partitions
  1476. >>> for i in binary_partitions(5):
  1477. ... print(i)
  1478. ...
  1479. [4, 1]
  1480. [2, 2, 1]
  1481. [2, 1, 1, 1]
  1482. [1, 1, 1, 1, 1]
  1483. References
  1484. ==========
  1485. .. [1] TAOCP 4, section 7.2.1.5, problem 64
  1486. """
  1487. from math import ceil, log
  1488. power = int(2**(ceil(log(n, 2))))
  1489. acc = 0
  1490. partition = []
  1491. while power:
  1492. if acc + power <= n:
  1493. partition.append(power)
  1494. acc += power
  1495. power >>= 1
  1496. last_num = len(partition) - 1 - (n & 1)
  1497. while last_num >= 0:
  1498. yield partition
  1499. if partition[last_num] == 2:
  1500. partition[last_num] = 1
  1501. partition.append(1)
  1502. last_num -= 1
  1503. continue
  1504. partition.append(1)
  1505. partition[last_num] >>= 1
  1506. x = partition[last_num + 1] = partition[last_num]
  1507. last_num += 1
  1508. while x > 1:
  1509. if x <= len(partition) - last_num - 1:
  1510. del partition[-x + 1:]
  1511. last_num += 1
  1512. partition[last_num] = x
  1513. else:
  1514. x >>= 1
  1515. yield [1]*n
  1516. def has_dups(seq):
  1517. """Return True if there are any duplicate elements in ``seq``.
  1518. Examples
  1519. ========
  1520. >>> from sympy import has_dups, Dict, Set
  1521. >>> has_dups((1, 2, 1))
  1522. True
  1523. >>> has_dups(range(3))
  1524. False
  1525. >>> all(has_dups(c) is False for c in (set(), Set(), dict(), Dict()))
  1526. True
  1527. """
  1528. from sympy.core.containers import Dict
  1529. from sympy.sets.sets import Set
  1530. if isinstance(seq, (dict, set, Dict, Set)):
  1531. return False
  1532. unique = set()
  1533. try:
  1534. return any(True for s in seq if s in unique or unique.add(s))
  1535. except TypeError:
  1536. return len(seq) != len(list(uniq(seq)))
  1537. def has_variety(seq):
  1538. """Return True if there are any different elements in ``seq``.
  1539. Examples
  1540. ========
  1541. >>> from sympy import has_variety
  1542. >>> has_variety((1, 2, 1))
  1543. True
  1544. >>> has_variety((1, 1, 1))
  1545. False
  1546. """
  1547. for i, s in enumerate(seq):
  1548. if i == 0:
  1549. sentinel = s
  1550. else:
  1551. if s != sentinel:
  1552. return True
  1553. return False
  1554. def uniq(seq, result=None):
  1555. """
  1556. Yield unique elements from ``seq`` as an iterator. The second
  1557. parameter ``result`` is used internally; it is not necessary
  1558. to pass anything for this.
  1559. Note: changing the sequence during iteration will raise a
  1560. RuntimeError if the size of the sequence is known; if you pass
  1561. an iterator and advance the iterator you will change the
  1562. output of this routine but there will be no warning.
  1563. Examples
  1564. ========
  1565. >>> from sympy.utilities.iterables import uniq
  1566. >>> dat = [1, 4, 1, 5, 4, 2, 1, 2]
  1567. >>> type(uniq(dat)) in (list, tuple)
  1568. False
  1569. >>> list(uniq(dat))
  1570. [1, 4, 5, 2]
  1571. >>> list(uniq(x for x in dat))
  1572. [1, 4, 5, 2]
  1573. >>> list(uniq([[1], [2, 1], [1]]))
  1574. [[1], [2, 1]]
  1575. """
  1576. try:
  1577. n = len(seq)
  1578. except TypeError:
  1579. n = None
  1580. def check():
  1581. # check that size of seq did not change during iteration;
  1582. # if n == None the object won't support size changing, e.g.
  1583. # an iterator can't be changed
  1584. if n is not None and len(seq) != n:
  1585. raise RuntimeError('sequence changed size during iteration')
  1586. try:
  1587. seen = set()
  1588. result = result or []
  1589. for i, s in enumerate(seq):
  1590. if not (s in seen or seen.add(s)):
  1591. yield s
  1592. check()
  1593. except TypeError:
  1594. if s not in result:
  1595. yield s
  1596. check()
  1597. result.append(s)
  1598. if hasattr(seq, '__getitem__'):
  1599. yield from uniq(seq[i + 1:], result)
  1600. else:
  1601. yield from uniq(seq, result)
  1602. def generate_bell(n):
  1603. """Return permutations of [0, 1, ..., n - 1] such that each permutation
  1604. differs from the last by the exchange of a single pair of neighbors.
  1605. The ``n!`` permutations are returned as an iterator. In order to obtain
  1606. the next permutation from a random starting permutation, use the
  1607. ``next_trotterjohnson`` method of the Permutation class (which generates
  1608. the same sequence in a different manner).
  1609. Examples
  1610. ========
  1611. >>> from itertools import permutations
  1612. >>> from sympy.utilities.iterables import generate_bell
  1613. >>> from sympy import zeros, Matrix
  1614. This is the sort of permutation used in the ringing of physical bells,
  1615. and does not produce permutations in lexicographical order. Rather, the
  1616. permutations differ from each other by exactly one inversion, and the
  1617. position at which the swapping occurs varies periodically in a simple
  1618. fashion. Consider the first few permutations of 4 elements generated
  1619. by ``permutations`` and ``generate_bell``:
  1620. >>> list(permutations(range(4)))[:5]
  1621. [(0, 1, 2, 3), (0, 1, 3, 2), (0, 2, 1, 3), (0, 2, 3, 1), (0, 3, 1, 2)]
  1622. >>> list(generate_bell(4))[:5]
  1623. [(0, 1, 2, 3), (0, 1, 3, 2), (0, 3, 1, 2), (3, 0, 1, 2), (3, 0, 2, 1)]
  1624. Notice how the 2nd and 3rd lexicographical permutations have 3 elements
  1625. out of place whereas each "bell" permutation always has only two
  1626. elements out of place relative to the previous permutation (and so the
  1627. signature (+/-1) of a permutation is opposite of the signature of the
  1628. previous permutation).
  1629. How the position of inversion varies across the elements can be seen
  1630. by tracing out where the largest number appears in the permutations:
  1631. >>> m = zeros(4, 24)
  1632. >>> for i, p in enumerate(generate_bell(4)):
  1633. ... m[:, i] = Matrix([j - 3 for j in list(p)]) # make largest zero
  1634. >>> m.print_nonzero('X')
  1635. [XXX XXXXXX XXXXXX XXX]
  1636. [XX XX XXXX XX XXXX XX XX]
  1637. [X XXXX XX XXXX XX XXXX X]
  1638. [ XXXXXX XXXXXX XXXXXX ]
  1639. See Also
  1640. ========
  1641. sympy.combinatorics.permutations.Permutation.next_trotterjohnson
  1642. References
  1643. ==========
  1644. .. [1] https://en.wikipedia.org/wiki/Method_ringing
  1645. .. [2] https://stackoverflow.com/questions/4856615/recursive-permutation/4857018
  1646. .. [3] https://web.archive.org/web/20160313023044/http://programminggeeks.com/bell-algorithm-for-permutation/
  1647. .. [4] https://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm
  1648. .. [5] Generating involutions, derangements, and relatives by ECO
  1649. Vincent Vajnovszki, DMTCS vol 1 issue 12, 2010
  1650. """
  1651. n = as_int(n)
  1652. if n < 1:
  1653. raise ValueError('n must be a positive integer')
  1654. if n == 1:
  1655. yield (0,)
  1656. elif n == 2:
  1657. yield (0, 1)
  1658. yield (1, 0)
  1659. elif n == 3:
  1660. yield from [(0, 1, 2), (0, 2, 1), (2, 0, 1), (2, 1, 0), (1, 2, 0), (1, 0, 2)]
  1661. else:
  1662. m = n - 1
  1663. op = [0] + [-1]*m
  1664. l = list(range(n))
  1665. while True:
  1666. yield tuple(l)
  1667. # find biggest element with op
  1668. big = None, -1 # idx, value
  1669. for i in range(n):
  1670. if op[i] and l[i] > big[1]:
  1671. big = i, l[i]
  1672. i, _ = big
  1673. if i is None:
  1674. break # there are no ops left
  1675. # swap it with neighbor in the indicated direction
  1676. j = i + op[i]
  1677. l[i], l[j] = l[j], l[i]
  1678. op[i], op[j] = op[j], op[i]
  1679. # if it landed at the end or if the neighbor in the same
  1680. # direction is bigger then turn off op
  1681. if j == 0 or j == m or l[j + op[j]] > l[j]:
  1682. op[j] = 0
  1683. # any element bigger to the left gets +1 op
  1684. for i in range(j):
  1685. if l[i] > l[j]:
  1686. op[i] = 1
  1687. # any element bigger to the right gets -1 op
  1688. for i in range(j + 1, n):
  1689. if l[i] > l[j]:
  1690. op[i] = -1
  1691. def generate_involutions(n):
  1692. """
  1693. Generates involutions.
  1694. An involution is a permutation that when multiplied
  1695. by itself equals the identity permutation. In this
  1696. implementation the involutions are generated using
  1697. Fixed Points.
  1698. Alternatively, an involution can be considered as
  1699. a permutation that does not contain any cycles with
  1700. a length that is greater than two.
  1701. Examples
  1702. ========
  1703. >>> from sympy.utilities.iterables import generate_involutions
  1704. >>> list(generate_involutions(3))
  1705. [(0, 1, 2), (0, 2, 1), (1, 0, 2), (2, 1, 0)]
  1706. >>> len(list(generate_involutions(4)))
  1707. 10
  1708. References
  1709. ==========
  1710. .. [1] https://mathworld.wolfram.com/PermutationInvolution.html
  1711. """
  1712. idx = list(range(n))
  1713. for p in permutations(idx):
  1714. for i in idx:
  1715. if p[p[i]] != i:
  1716. break
  1717. else:
  1718. yield p
  1719. def multiset_derangements(s):
  1720. """Generate derangements of the elements of s *in place*.
  1721. Examples
  1722. ========
  1723. >>> from sympy.utilities.iterables import multiset_derangements, uniq
  1724. Because the derangements of multisets (not sets) are generated
  1725. in place, copies of the return value must be made if a collection
  1726. of derangements is desired or else all values will be the same:
  1727. >>> list(uniq([i for i in multiset_derangements('1233')]))
  1728. [[None, None, None, None]]
  1729. >>> [i.copy() for i in multiset_derangements('1233')]
  1730. [['3', '3', '1', '2'], ['3', '3', '2', '1']]
  1731. >>> [''.join(i) for i in multiset_derangements('1233')]
  1732. ['3312', '3321']
  1733. """
  1734. from sympy.core.sorting import ordered
  1735. # create multiset dictionary of hashable elements or else
  1736. # remap elements to integers
  1737. try:
  1738. ms = multiset(s)
  1739. except TypeError:
  1740. # give each element a canonical integer value
  1741. key = dict(enumerate(ordered(uniq(s))))
  1742. h = []
  1743. for si in s:
  1744. for k in key:
  1745. if key[k] == si:
  1746. h.append(k)
  1747. break
  1748. for i in multiset_derangements(h):
  1749. yield [key[j] for j in i]
  1750. return
  1751. mx = max(ms.values()) # max repetition of any element
  1752. n = len(s) # the number of elements
  1753. ## special cases
  1754. # 1) one element has more than half the total cardinality of s: no
  1755. # derangements are possible.
  1756. if mx*2 > n:
  1757. return
  1758. # 2) all elements appear once: singletons
  1759. if len(ms) == n:
  1760. yield from _set_derangements(s)
  1761. return
  1762. # find the first element that is repeated the most to place
  1763. # in the following two special cases where the selection
  1764. # is unambiguous: either there are two elements with multiplicity
  1765. # of mx or else there is only one with multiplicity mx
  1766. for M in ms:
  1767. if ms[M] == mx:
  1768. break
  1769. inonM = [i for i in range(n) if s[i] != M] # location of non-M
  1770. iM = [i for i in range(n) if s[i] == M] # locations of M
  1771. rv = [None]*n
  1772. # 3) half are the same
  1773. if 2*mx == n:
  1774. # M goes into non-M locations
  1775. for i in inonM:
  1776. rv[i] = M
  1777. # permutations of non-M go to M locations
  1778. for p in multiset_permutations([s[i] for i in inonM]):
  1779. for i, pi in zip(iM, p):
  1780. rv[i] = pi
  1781. yield rv
  1782. # clean-up (and encourages proper use of routine)
  1783. rv[:] = [None]*n
  1784. return
  1785. # 4) single repeat covers all but 1 of the non-repeats:
  1786. # if there is one repeat then the multiset of the values
  1787. # of ms would be {mx: 1, 1: n - mx}, i.e. there would
  1788. # be n - mx + 1 values with the condition that n - 2*mx = 1
  1789. if n - 2*mx == 1 and len(ms.values()) == n - mx + 1:
  1790. for i, i1 in enumerate(inonM):
  1791. ifill = inonM[:i] + inonM[i+1:]
  1792. for j in ifill:
  1793. rv[j] = M
  1794. for p in permutations([s[j] for j in ifill]):
  1795. rv[i1] = s[i1]
  1796. for j, pi in zip(iM, p):
  1797. rv[j] = pi
  1798. k = i1
  1799. for j in iM:
  1800. rv[j], rv[k] = rv[k], rv[j]
  1801. yield rv
  1802. k = j
  1803. # clean-up (and encourages proper use of routine)
  1804. rv[:] = [None]*n
  1805. return
  1806. ## general case is handled with 3 helpers:
  1807. # 1) `finish_derangements` will place the last two elements
  1808. # which have arbitrary multiplicities, e.g. for multiset
  1809. # {c: 3, a: 2, b: 2}, the last two elements are a and b
  1810. # 2) `iopen` will tell where a given element can be placed
  1811. # 3) `do` will recursively place elements into subsets of
  1812. # valid locations
  1813. def finish_derangements():
  1814. """Place the last two elements into the partially completed
  1815. derangement, and yield the results.
  1816. """
  1817. a = take[1][0] # penultimate element
  1818. a_ct = take[1][1]
  1819. b = take[0][0] # last element to be placed
  1820. b_ct = take[0][1]
  1821. # split the indexes of the not-already-assigned elements of rv into
  1822. # three categories
  1823. forced_a = [] # positions which must have an a
  1824. forced_b = [] # positions which must have a b
  1825. open_free = [] # positions which could take either
  1826. for i in range(len(s)):
  1827. if rv[i] is None:
  1828. if s[i] == a:
  1829. forced_b.append(i)
  1830. elif s[i] == b:
  1831. forced_a.append(i)
  1832. else:
  1833. open_free.append(i)
  1834. if len(forced_a) > a_ct or len(forced_b) > b_ct:
  1835. # No derangement possible
  1836. return
  1837. for i in forced_a:
  1838. rv[i] = a
  1839. for i in forced_b:
  1840. rv[i] = b
  1841. for a_place in combinations(open_free, a_ct - len(forced_a)):
  1842. for a_pos in a_place:
  1843. rv[a_pos] = a
  1844. for i in open_free:
  1845. if rv[i] is None: # anything not in the subset is set to b
  1846. rv[i] = b
  1847. yield rv
  1848. # Clean up/undo the final placements
  1849. for i in open_free:
  1850. rv[i] = None
  1851. # additional cleanup - clear forced_a, forced_b
  1852. for i in forced_a:
  1853. rv[i] = None
  1854. for i in forced_b:
  1855. rv[i] = None
  1856. def iopen(v):
  1857. # return indices at which element v can be placed in rv:
  1858. # locations which are not already occupied if that location
  1859. # does not already contain v in the same location of s
  1860. return [i for i in range(n) if rv[i] is None and s[i] != v]
  1861. def do(j):
  1862. if j == 1:
  1863. # handle the last two elements (regardless of multiplicity)
  1864. # with a special method
  1865. yield from finish_derangements()
  1866. else:
  1867. # place the mx elements of M into a subset of places
  1868. # into which it can be replaced
  1869. M, mx = take[j]
  1870. for i in combinations(iopen(M), mx):
  1871. # place M
  1872. for ii in i:
  1873. rv[ii] = M
  1874. # recursively place the next element
  1875. yield from do(j - 1)
  1876. # mark positions where M was placed as once again
  1877. # open for placement of other elements
  1878. for ii in i:
  1879. rv[ii] = None
  1880. # process elements in order of canonically decreasing multiplicity
  1881. take = sorted(ms.items(), key=lambda x:(x[1], x[0]))
  1882. yield from do(len(take) - 1)
  1883. rv[:] = [None]*n
  1884. def random_derangement(t, choice=None, strict=True):
  1885. """Return a list of elements in which none are in the same positions
  1886. as they were originally. If an element fills more than half of the positions
  1887. then an error will be raised since no derangement is possible. To obtain
  1888. a derangement of as many items as possible--with some of the most numerous
  1889. remaining in their original positions--pass `strict=False`. To produce a
  1890. pseudorandom derangment, pass a pseudorandom selector like `choice` (see
  1891. below).
  1892. Examples
  1893. ========
  1894. >>> from sympy.utilities.iterables import random_derangement
  1895. >>> t = 'SymPy: a CAS in pure Python'
  1896. >>> d = random_derangement(t)
  1897. >>> all(i != j for i, j in zip(d, t))
  1898. True
  1899. A predictable result can be obtained by using a pseudorandom
  1900. generator for the choice:
  1901. >>> from sympy.core.random import seed, choice as c
  1902. >>> seed(1)
  1903. >>> d = [''.join(random_derangement(t, c)) for i in range(5)]
  1904. >>> assert len(set(d)) != 1 # we got different values
  1905. By reseeding, the same sequence can be obtained:
  1906. >>> seed(1)
  1907. >>> d2 = [''.join(random_derangement(t, c)) for i in range(5)]
  1908. >>> assert d == d2
  1909. """
  1910. if choice is None:
  1911. import secrets
  1912. choice = secrets.choice
  1913. def shuffle(rv):
  1914. '''Knuth shuffle'''
  1915. for i in range(len(rv) - 1, 0, -1):
  1916. x = choice(rv[:i + 1])
  1917. j = rv.index(x)
  1918. rv[i], rv[j] = rv[j], rv[i]
  1919. def pick(rv, n):
  1920. '''shuffle rv and return the first n values
  1921. '''
  1922. shuffle(rv)
  1923. return rv[:n]
  1924. ms = multiset(t)
  1925. tot = len(t)
  1926. ms = sorted(ms.items(), key=lambda x: x[1])
  1927. # if there are not enough spaces for the most
  1928. # plentiful element to move to then some of them
  1929. # will have to stay in place
  1930. M, mx = ms[-1]
  1931. n = len(t)
  1932. xs = 2*mx - tot
  1933. if xs > 0:
  1934. if strict:
  1935. raise ValueError('no derangement possible')
  1936. opts = [i for (i, c) in enumerate(t) if c == ms[-1][0]]
  1937. pick(opts, xs)
  1938. stay = sorted(opts[:xs])
  1939. rv = list(t)
  1940. for i in reversed(stay):
  1941. rv.pop(i)
  1942. rv = random_derangement(rv, choice)
  1943. for i in stay:
  1944. rv.insert(i, ms[-1][0])
  1945. return ''.join(rv) if type(t) is str else rv
  1946. # the normal derangement calculated from here
  1947. if n == len(ms):
  1948. # approx 1/3 will succeed
  1949. rv = list(t)
  1950. while True:
  1951. shuffle(rv)
  1952. if all(i != j for i,j in zip(rv, t)):
  1953. break
  1954. else:
  1955. # general case
  1956. rv = [None]*n
  1957. while True:
  1958. j = 0
  1959. while j > -len(ms): # do most numerous first
  1960. j -= 1
  1961. e, c = ms[j]
  1962. opts = [i for i in range(n) if rv[i] is None and t[i] != e]
  1963. if len(opts) < c:
  1964. for i in range(n):
  1965. rv[i] = None
  1966. break # try again
  1967. pick(opts, c)
  1968. for i in range(c):
  1969. rv[opts[i]] = e
  1970. else:
  1971. return rv
  1972. return rv
  1973. def _set_derangements(s):
  1974. """
  1975. yield derangements of items in ``s`` which are assumed to contain
  1976. no repeated elements
  1977. """
  1978. if len(s) < 2:
  1979. return
  1980. if len(s) == 2:
  1981. yield [s[1], s[0]]
  1982. return
  1983. if len(s) == 3:
  1984. yield [s[1], s[2], s[0]]
  1985. yield [s[2], s[0], s[1]]
  1986. return
  1987. for p in permutations(s):
  1988. if not any(i == j for i, j in zip(p, s)):
  1989. yield list(p)
  1990. def generate_derangements(s):
  1991. """
  1992. Return unique derangements of the elements of iterable ``s``.
  1993. Examples
  1994. ========
  1995. >>> from sympy.utilities.iterables import generate_derangements
  1996. >>> list(generate_derangements([0, 1, 2]))
  1997. [[1, 2, 0], [2, 0, 1]]
  1998. >>> list(generate_derangements([0, 1, 2, 2]))
  1999. [[2, 2, 0, 1], [2, 2, 1, 0]]
  2000. >>> list(generate_derangements([0, 1, 1]))
  2001. []
  2002. See Also
  2003. ========
  2004. sympy.functions.combinatorial.factorials.subfactorial
  2005. """
  2006. if not has_dups(s):
  2007. yield from _set_derangements(s)
  2008. else:
  2009. for p in multiset_derangements(s):
  2010. yield list(p)
  2011. def necklaces(n, k, free=False):
  2012. """
  2013. A routine to generate necklaces that may (free=True) or may not
  2014. (free=False) be turned over to be viewed. The "necklaces" returned
  2015. are comprised of ``n`` integers (beads) with ``k`` different
  2016. values (colors). Only unique necklaces are returned.
  2017. Examples
  2018. ========
  2019. >>> from sympy.utilities.iterables import necklaces, bracelets
  2020. >>> def show(s, i):
  2021. ... return ''.join(s[j] for j in i)
  2022. The "unrestricted necklace" is sometimes also referred to as a
  2023. "bracelet" (an object that can be turned over, a sequence that can
  2024. be reversed) and the term "necklace" is used to imply a sequence
  2025. that cannot be reversed. So ACB == ABC for a bracelet (rotate and
  2026. reverse) while the two are different for a necklace since rotation
  2027. alone cannot make the two sequences the same.
  2028. (mnemonic: Bracelets can be viewed Backwards, but Not Necklaces.)
  2029. >>> B = [show('ABC', i) for i in bracelets(3, 3)]
  2030. >>> N = [show('ABC', i) for i in necklaces(3, 3)]
  2031. >>> set(N) - set(B)
  2032. {'ACB'}
  2033. >>> list(necklaces(4, 2))
  2034. [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 1),
  2035. (0, 1, 0, 1), (0, 1, 1, 1), (1, 1, 1, 1)]
  2036. >>> [show('.o', i) for i in bracelets(4, 2)]
  2037. ['....', '...o', '..oo', '.o.o', '.ooo', 'oooo']
  2038. References
  2039. ==========
  2040. .. [1] https://mathworld.wolfram.com/Necklace.html
  2041. .. [2] Frank Ruskey, Carla Savage, and Terry Min Yih Wang,
  2042. Generating necklaces, Journal of Algorithms 13 (1992), 414-430;
  2043. https://doi.org/10.1016/0196-6774(92)90047-G
  2044. """
  2045. # The FKM algorithm
  2046. if k == 0 and n > 0:
  2047. return
  2048. a = [0]*n
  2049. yield tuple(a)
  2050. if n == 0:
  2051. return
  2052. while True:
  2053. i = n - 1
  2054. while a[i] == k - 1:
  2055. i -= 1
  2056. if i == -1:
  2057. return
  2058. a[i] += 1
  2059. for j in range(n - i - 1):
  2060. a[j + i + 1] = a[j]
  2061. if n % (i + 1) == 0 and (not free or all(a <= a[j::-1] + a[-1:j:-1] for j in range(n - 1))):
  2062. # No need to test j = n - 1.
  2063. yield tuple(a)
  2064. def bracelets(n, k):
  2065. """Wrapper to necklaces to return a free (unrestricted) necklace."""
  2066. return necklaces(n, k, free=True)
  2067. def generate_oriented_forest(n):
  2068. """
  2069. This algorithm generates oriented forests.
  2070. An oriented graph is a directed graph having no symmetric pair of directed
  2071. edges. A forest is an acyclic graph, i.e., it has no cycles. A forest can
  2072. also be described as a disjoint union of trees, which are graphs in which
  2073. any two vertices are connected by exactly one simple path.
  2074. Examples
  2075. ========
  2076. >>> from sympy.utilities.iterables import generate_oriented_forest
  2077. >>> list(generate_oriented_forest(4))
  2078. [[0, 1, 2, 3], [0, 1, 2, 2], [0, 1, 2, 1], [0, 1, 2, 0], \
  2079. [0, 1, 1, 1], [0, 1, 1, 0], [0, 1, 0, 1], [0, 1, 0, 0], [0, 0, 0, 0]]
  2080. References
  2081. ==========
  2082. .. [1] T. Beyer and S.M. Hedetniemi: constant time generation of
  2083. rooted trees, SIAM J. Computing Vol. 9, No. 4, November 1980
  2084. .. [2] https://stackoverflow.com/questions/1633833/oriented-forest-taocp-algorithm-in-python
  2085. """
  2086. P = list(range(-1, n))
  2087. while True:
  2088. yield P[1:]
  2089. if P[n] > 0:
  2090. P[n] = P[P[n]]
  2091. else:
  2092. for p in range(n - 1, 0, -1):
  2093. if P[p] != 0:
  2094. target = P[p] - 1
  2095. for q in range(p - 1, 0, -1):
  2096. if P[q] == target:
  2097. break
  2098. offset = p - q
  2099. for i in range(p, n + 1):
  2100. P[i] = P[i - offset]
  2101. break
  2102. else:
  2103. break
  2104. def minlex(seq, directed=True, key=None):
  2105. r"""
  2106. Return the rotation of the sequence in which the lexically smallest
  2107. elements appear first, e.g. `cba \rightarrow acb`.
  2108. The sequence returned is a tuple, unless the input sequence is a string
  2109. in which case a string is returned.
  2110. If ``directed`` is False then the smaller of the sequence and the
  2111. reversed sequence is returned, e.g. `cba \rightarrow abc`.
  2112. If ``key`` is not None then it is used to extract a comparison key from each element in iterable.
  2113. Examples
  2114. ========
  2115. >>> from sympy.combinatorics.polyhedron import minlex
  2116. >>> minlex((1, 2, 0))
  2117. (0, 1, 2)
  2118. >>> minlex((1, 0, 2))
  2119. (0, 2, 1)
  2120. >>> minlex((1, 0, 2), directed=False)
  2121. (0, 1, 2)
  2122. >>> minlex('11010011000', directed=True)
  2123. '00011010011'
  2124. >>> minlex('11010011000', directed=False)
  2125. '00011001011'
  2126. >>> minlex(('bb', 'aaa', 'c', 'a'))
  2127. ('a', 'bb', 'aaa', 'c')
  2128. >>> minlex(('bb', 'aaa', 'c', 'a'), key=len)
  2129. ('c', 'a', 'bb', 'aaa')
  2130. """
  2131. from sympy.functions.elementary.miscellaneous import Id
  2132. if key is None: key = Id
  2133. best = rotate_left(seq, least_rotation(seq, key=key))
  2134. if not directed:
  2135. rseq = seq[::-1]
  2136. rbest = rotate_left(rseq, least_rotation(rseq, key=key))
  2137. best = min(best, rbest, key=key)
  2138. # Convert to tuple, unless we started with a string.
  2139. return tuple(best) if not isinstance(seq, str) else best
  2140. def runs(seq, op=gt):
  2141. """Group the sequence into lists in which successive elements
  2142. all compare the same with the comparison operator, ``op``:
  2143. op(seq[i + 1], seq[i]) is True from all elements in a run.
  2144. Examples
  2145. ========
  2146. >>> from sympy.utilities.iterables import runs
  2147. >>> from operator import ge
  2148. >>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2])
  2149. [[0, 1, 2], [2], [1, 4], [3], [2], [2]]
  2150. >>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2], op=ge)
  2151. [[0, 1, 2, 2], [1, 4], [3], [2, 2]]
  2152. """
  2153. cycles = []
  2154. seq = iter(seq)
  2155. try:
  2156. run = [next(seq)]
  2157. except StopIteration:
  2158. return []
  2159. while True:
  2160. try:
  2161. ei = next(seq)
  2162. except StopIteration:
  2163. break
  2164. if op(ei, run[-1]):
  2165. run.append(ei)
  2166. continue
  2167. else:
  2168. cycles.append(run)
  2169. run = [ei]
  2170. if run:
  2171. cycles.append(run)
  2172. return cycles
  2173. def sequence_partitions(l, n, /):
  2174. r"""Returns the partition of sequence $l$ into $n$ bins
  2175. Explanation
  2176. ===========
  2177. Given the sequence $l_1 \cdots l_m \in V^+$ where
  2178. $V^+$ is the Kleene plus of $V$
  2179. The set of $n$ partitions of $l$ is defined as:
  2180. .. math::
  2181. \{(s_1, \cdots, s_n) | s_1 \in V^+, \cdots, s_n \in V^+,
  2182. s_1 \cdots s_n = l_1 \cdots l_m\}
  2183. Parameters
  2184. ==========
  2185. l : Sequence[T]
  2186. A nonempty sequence of any Python objects
  2187. n : int
  2188. A positive integer
  2189. Yields
  2190. ======
  2191. out : list[Sequence[T]]
  2192. A list of sequences with concatenation equals $l$.
  2193. This should conform with the type of $l$.
  2194. Examples
  2195. ========
  2196. >>> from sympy.utilities.iterables import sequence_partitions
  2197. >>> for out in sequence_partitions([1, 2, 3, 4], 2):
  2198. ... print(out)
  2199. [[1], [2, 3, 4]]
  2200. [[1, 2], [3, 4]]
  2201. [[1, 2, 3], [4]]
  2202. Notes
  2203. =====
  2204. This is modified version of EnricoGiampieri's partition generator
  2205. from https://stackoverflow.com/questions/13131491/partition-n-items-into-k-bins-in-python-lazily
  2206. See Also
  2207. ========
  2208. sequence_partitions_empty
  2209. """
  2210. # Asserting l is nonempty is done only for sanity check
  2211. if n == 1 and l:
  2212. yield [l]
  2213. return
  2214. for i in range(1, len(l)):
  2215. for part in sequence_partitions(l[i:], n - 1):
  2216. yield [l[:i]] + part
  2217. def sequence_partitions_empty(l, n, /):
  2218. r"""Returns the partition of sequence $l$ into $n$ bins with
  2219. empty sequence
  2220. Explanation
  2221. ===========
  2222. Given the sequence $l_1 \cdots l_m \in V^*$ where
  2223. $V^*$ is the Kleene star of $V$
  2224. The set of $n$ partitions of $l$ is defined as:
  2225. .. math::
  2226. \{(s_1, \cdots, s_n) | s_1 \in V^*, \cdots, s_n \in V^*,
  2227. s_1 \cdots s_n = l_1 \cdots l_m\}
  2228. There are more combinations than :func:`sequence_partitions` because
  2229. empty sequence can fill everywhere, so we try to provide different
  2230. utility for this.
  2231. Parameters
  2232. ==========
  2233. l : Sequence[T]
  2234. A sequence of any Python objects (can be possibly empty)
  2235. n : int
  2236. A positive integer
  2237. Yields
  2238. ======
  2239. out : list[Sequence[T]]
  2240. A list of sequences with concatenation equals $l$.
  2241. This should conform with the type of $l$.
  2242. Examples
  2243. ========
  2244. >>> from sympy.utilities.iterables import sequence_partitions_empty
  2245. >>> for out in sequence_partitions_empty([1, 2, 3, 4], 2):
  2246. ... print(out)
  2247. [[], [1, 2, 3, 4]]
  2248. [[1], [2, 3, 4]]
  2249. [[1, 2], [3, 4]]
  2250. [[1, 2, 3], [4]]
  2251. [[1, 2, 3, 4], []]
  2252. See Also
  2253. ========
  2254. sequence_partitions
  2255. """
  2256. if n < 1:
  2257. return
  2258. if n == 1:
  2259. yield [l]
  2260. return
  2261. for i in range(0, len(l) + 1):
  2262. for part in sequence_partitions_empty(l[i:], n - 1):
  2263. yield [l[:i]] + part
  2264. def kbins(l, k, ordered=None):
  2265. """
  2266. Return sequence ``l`` partitioned into ``k`` bins.
  2267. Examples
  2268. ========
  2269. The default is to give the items in the same order, but grouped
  2270. into k partitions without any reordering:
  2271. >>> from sympy.utilities.iterables import kbins
  2272. >>> for p in kbins(list(range(5)), 2):
  2273. ... print(p)
  2274. ...
  2275. [[0], [1, 2, 3, 4]]
  2276. [[0, 1], [2, 3, 4]]
  2277. [[0, 1, 2], [3, 4]]
  2278. [[0, 1, 2, 3], [4]]
  2279. The ``ordered`` flag is either None (to give the simple partition
  2280. of the elements) or is a 2 digit integer indicating whether the order of
  2281. the bins and the order of the items in the bins matters. Given::
  2282. A = [[0], [1, 2]]
  2283. B = [[1, 2], [0]]
  2284. C = [[2, 1], [0]]
  2285. D = [[0], [2, 1]]
  2286. the following values for ``ordered`` have the shown meanings::
  2287. 00 means A == B == C == D
  2288. 01 means A == B
  2289. 10 means A == D
  2290. 11 means A == A
  2291. >>> for ordered_flag in [None, 0, 1, 10, 11]:
  2292. ... print('ordered = %s' % ordered_flag)
  2293. ... for p in kbins(list(range(3)), 2, ordered=ordered_flag):
  2294. ... print(' %s' % p)
  2295. ...
  2296. ordered = None
  2297. [[0], [1, 2]]
  2298. [[0, 1], [2]]
  2299. ordered = 0
  2300. [[0, 1], [2]]
  2301. [[0, 2], [1]]
  2302. [[0], [1, 2]]
  2303. ordered = 1
  2304. [[0], [1, 2]]
  2305. [[0], [2, 1]]
  2306. [[1], [0, 2]]
  2307. [[1], [2, 0]]
  2308. [[2], [0, 1]]
  2309. [[2], [1, 0]]
  2310. ordered = 10
  2311. [[0, 1], [2]]
  2312. [[2], [0, 1]]
  2313. [[0, 2], [1]]
  2314. [[1], [0, 2]]
  2315. [[0], [1, 2]]
  2316. [[1, 2], [0]]
  2317. ordered = 11
  2318. [[0], [1, 2]]
  2319. [[0, 1], [2]]
  2320. [[0], [2, 1]]
  2321. [[0, 2], [1]]
  2322. [[1], [0, 2]]
  2323. [[1, 0], [2]]
  2324. [[1], [2, 0]]
  2325. [[1, 2], [0]]
  2326. [[2], [0, 1]]
  2327. [[2, 0], [1]]
  2328. [[2], [1, 0]]
  2329. [[2, 1], [0]]
  2330. See Also
  2331. ========
  2332. partitions, multiset_partitions
  2333. """
  2334. if ordered is None:
  2335. yield from sequence_partitions(l, k)
  2336. elif ordered == 11:
  2337. for pl in multiset_permutations(l):
  2338. pl = list(pl)
  2339. yield from sequence_partitions(pl, k)
  2340. elif ordered == 00:
  2341. yield from multiset_partitions(l, k)
  2342. elif ordered == 10:
  2343. for p in multiset_partitions(l, k):
  2344. for perm in permutations(p):
  2345. yield list(perm)
  2346. elif ordered == 1:
  2347. for kgot, p in partitions(len(l), k, size=True):
  2348. if kgot != k:
  2349. continue
  2350. for li in multiset_permutations(l):
  2351. rv = []
  2352. i = j = 0
  2353. li = list(li)
  2354. for size, multiplicity in sorted(p.items()):
  2355. for m in range(multiplicity):
  2356. j = i + size
  2357. rv.append(li[i: j])
  2358. i = j
  2359. yield rv
  2360. else:
  2361. raise ValueError(
  2362. 'ordered must be one of 00, 01, 10 or 11, not %s' % ordered)
  2363. def permute_signs(t):
  2364. """Return iterator in which the signs of non-zero elements
  2365. of t are permuted.
  2366. Examples
  2367. ========
  2368. >>> from sympy.utilities.iterables import permute_signs
  2369. >>> list(permute_signs((0, 1, 2)))
  2370. [(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2)]
  2371. """
  2372. for signs in product(*[(1, -1)]*(len(t) - t.count(0))):
  2373. signs = list(signs)
  2374. yield type(t)([i*signs.pop() if i else i for i in t])
  2375. def signed_permutations(t):
  2376. """Return iterator in which the signs of non-zero elements
  2377. of t and the order of the elements are permuted.
  2378. Examples
  2379. ========
  2380. >>> from sympy.utilities.iterables import signed_permutations
  2381. >>> list(signed_permutations((0, 1, 2)))
  2382. [(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2), (0, 2, 1),
  2383. (0, -2, 1), (0, 2, -1), (0, -2, -1), (1, 0, 2), (-1, 0, 2),
  2384. (1, 0, -2), (-1, 0, -2), (1, 2, 0), (-1, 2, 0), (1, -2, 0),
  2385. (-1, -2, 0), (2, 0, 1), (-2, 0, 1), (2, 0, -1), (-2, 0, -1),
  2386. (2, 1, 0), (-2, 1, 0), (2, -1, 0), (-2, -1, 0)]
  2387. """
  2388. return (type(t)(i) for j in permutations(t)
  2389. for i in permute_signs(j))
  2390. def rotations(s, dir=1):
  2391. """Return a generator giving the items in s as list where
  2392. each subsequent list has the items rotated to the left (default)
  2393. or right (``dir=-1``) relative to the previous list.
  2394. Examples
  2395. ========
  2396. >>> from sympy import rotations
  2397. >>> list(rotations([1,2,3]))
  2398. [[1, 2, 3], [2, 3, 1], [3, 1, 2]]
  2399. >>> list(rotations([1,2,3], -1))
  2400. [[1, 2, 3], [3, 1, 2], [2, 3, 1]]
  2401. """
  2402. seq = list(s)
  2403. for i in range(len(seq)):
  2404. yield seq
  2405. seq = rotate_left(seq, dir)
  2406. def roundrobin(*iterables):
  2407. """roundrobin recipe taken from itertools documentation:
  2408. https://docs.python.org/3/library/itertools.html#itertools-recipes
  2409. roundrobin('ABC', 'D', 'EF') --> A D E B F C
  2410. Recipe credited to George Sakkis
  2411. """
  2412. nexts = cycle(iter(it).__next__ for it in iterables)
  2413. pending = len(iterables)
  2414. while pending:
  2415. try:
  2416. for nxt in nexts:
  2417. yield nxt()
  2418. except StopIteration:
  2419. pending -= 1
  2420. nexts = cycle(islice(nexts, pending))
  2421. class NotIterable:
  2422. """
  2423. Use this as mixin when creating a class which is not supposed to
  2424. return true when iterable() is called on its instances because
  2425. calling list() on the instance, for example, would result in
  2426. an infinite loop.
  2427. """
  2428. pass
  2429. def iterable(i, exclude=(str, dict, NotIterable)):
  2430. """
  2431. Return a boolean indicating whether ``i`` is SymPy iterable.
  2432. True also indicates that the iterator is finite, e.g. you can
  2433. call list(...) on the instance.
  2434. When SymPy is working with iterables, it is almost always assuming
  2435. that the iterable is not a string or a mapping, so those are excluded
  2436. by default. If you want a pure Python definition, make exclude=None. To
  2437. exclude multiple items, pass them as a tuple.
  2438. You can also set the _iterable attribute to True or False on your class,
  2439. which will override the checks here, including the exclude test.
  2440. As a rule of thumb, some SymPy functions use this to check if they should
  2441. recursively map over an object. If an object is technically iterable in
  2442. the Python sense but does not desire this behavior (e.g., because its
  2443. iteration is not finite, or because iteration might induce an unwanted
  2444. computation), it should disable it by setting the _iterable attribute to False.
  2445. See also: is_sequence
  2446. Examples
  2447. ========
  2448. >>> from sympy.utilities.iterables import iterable
  2449. >>> from sympy import Tuple
  2450. >>> things = [[1], (1,), set([1]), Tuple(1), (j for j in [1, 2]), {1:2}, '1', 1]
  2451. >>> for i in things:
  2452. ... print('%s %s' % (iterable(i), type(i)))
  2453. True <... 'list'>
  2454. True <... 'tuple'>
  2455. True <... 'set'>
  2456. True <class 'sympy.core.containers.Tuple'>
  2457. True <... 'generator'>
  2458. False <... 'dict'>
  2459. False <... 'str'>
  2460. False <... 'int'>
  2461. >>> iterable({}, exclude=None)
  2462. True
  2463. >>> iterable({}, exclude=str)
  2464. True
  2465. >>> iterable("no", exclude=str)
  2466. False
  2467. """
  2468. if hasattr(i, '_iterable'):
  2469. return i._iterable
  2470. try:
  2471. iter(i)
  2472. except TypeError:
  2473. return False
  2474. if exclude:
  2475. return not isinstance(i, exclude)
  2476. return True
  2477. def is_sequence(i, include=None):
  2478. """
  2479. Return a boolean indicating whether ``i`` is a sequence in the SymPy
  2480. sense. If anything that fails the test below should be included as
  2481. being a sequence for your application, set 'include' to that object's
  2482. type; multiple types should be passed as a tuple of types.
  2483. Note: although generators can generate a sequence, they often need special
  2484. handling to make sure their elements are captured before the generator is
  2485. exhausted, so these are not included by default in the definition of a
  2486. sequence.
  2487. See also: iterable
  2488. Examples
  2489. ========
  2490. >>> from sympy.utilities.iterables import is_sequence
  2491. >>> from types import GeneratorType
  2492. >>> is_sequence([])
  2493. True
  2494. >>> is_sequence(set())
  2495. False
  2496. >>> is_sequence('abc')
  2497. False
  2498. >>> is_sequence('abc', include=str)
  2499. True
  2500. >>> generator = (c for c in 'abc')
  2501. >>> is_sequence(generator)
  2502. False
  2503. >>> is_sequence(generator, include=(str, GeneratorType))
  2504. True
  2505. """
  2506. return (hasattr(i, '__getitem__') and
  2507. iterable(i) or
  2508. bool(include) and
  2509. isinstance(i, include))
  2510. @deprecated(
  2511. """
  2512. Using postorder_traversal from the sympy.utilities.iterables submodule is
  2513. deprecated.
  2514. Instead, use postorder_traversal from the top-level sympy namespace, like
  2515. sympy.postorder_traversal
  2516. """,
  2517. deprecated_since_version="1.10",
  2518. active_deprecations_target="deprecated-traversal-functions-moved")
  2519. def postorder_traversal(node, keys=None):
  2520. from sympy.core.traversal import postorder_traversal as _postorder_traversal
  2521. return _postorder_traversal(node, keys=keys)
  2522. @deprecated(
  2523. """
  2524. Using interactive_traversal from the sympy.utilities.iterables submodule
  2525. is deprecated.
  2526. Instead, use interactive_traversal from the top-level sympy namespace,
  2527. like
  2528. sympy.interactive_traversal
  2529. """,
  2530. deprecated_since_version="1.10",
  2531. active_deprecations_target="deprecated-traversal-functions-moved")
  2532. def interactive_traversal(expr):
  2533. from sympy.interactive.traversal import interactive_traversal as _interactive_traversal
  2534. return _interactive_traversal(expr)
  2535. @deprecated(
  2536. """
  2537. Importing default_sort_key from sympy.utilities.iterables is deprecated.
  2538. Use from sympy import default_sort_key instead.
  2539. """,
  2540. deprecated_since_version="1.10",
  2541. active_deprecations_target="deprecated-sympy-core-compatibility",
  2542. )
  2543. def default_sort_key(*args, **kwargs):
  2544. from sympy import default_sort_key as _default_sort_key
  2545. return _default_sort_key(*args, **kwargs)
  2546. @deprecated(
  2547. """
  2548. Importing default_sort_key from sympy.utilities.iterables is deprecated.
  2549. Use from sympy import default_sort_key instead.
  2550. """,
  2551. deprecated_since_version="1.10",
  2552. active_deprecations_target="deprecated-sympy-core-compatibility",
  2553. )
  2554. def ordered(*args, **kwargs):
  2555. from sympy import ordered as _ordered
  2556. return _ordered(*args, **kwargs)