iterables.py 89 KB

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