permutations.py 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112
  1. import random
  2. from collections import defaultdict
  3. from collections.abc import Iterable
  4. from functools import reduce
  5. from sympy.core.parameters import global_parameters
  6. from sympy.core.basic import Atom
  7. from sympy.core.expr import Expr
  8. from sympy.core.numbers import Integer
  9. from sympy.core.sympify import _sympify
  10. from sympy.matrices import zeros
  11. from sympy.polys.polytools import lcm
  12. from sympy.printing.repr import srepr
  13. from sympy.utilities.iterables import (flatten, has_variety, minlex,
  14. has_dups, runs, is_sequence)
  15. from sympy.utilities.misc import as_int
  16. from mpmath.libmp.libintmath import ifac
  17. from sympy.multipledispatch import dispatch
  18. def _af_rmul(a, b):
  19. """
  20. Return the product b*a; input and output are array forms. The ith value
  21. is a[b[i]].
  22. Examples
  23. ========
  24. >>> from sympy.combinatorics.permutations import _af_rmul, Permutation
  25. >>> a, b = [1, 0, 2], [0, 2, 1]
  26. >>> _af_rmul(a, b)
  27. [1, 2, 0]
  28. >>> [a[b[i]] for i in range(3)]
  29. [1, 2, 0]
  30. This handles the operands in reverse order compared to the ``*`` operator:
  31. >>> a = Permutation(a)
  32. >>> b = Permutation(b)
  33. >>> list(a*b)
  34. [2, 0, 1]
  35. >>> [b(a(i)) for i in range(3)]
  36. [2, 0, 1]
  37. See Also
  38. ========
  39. rmul, _af_rmuln
  40. """
  41. return [a[i] for i in b]
  42. def _af_rmuln(*abc):
  43. """
  44. Given [a, b, c, ...] return the product of ...*c*b*a using array forms.
  45. The ith value is a[b[c[i]]].
  46. Examples
  47. ========
  48. >>> from sympy.combinatorics.permutations import _af_rmul, Permutation
  49. >>> a, b = [1, 0, 2], [0, 2, 1]
  50. >>> _af_rmul(a, b)
  51. [1, 2, 0]
  52. >>> [a[b[i]] for i in range(3)]
  53. [1, 2, 0]
  54. This handles the operands in reverse order compared to the ``*`` operator:
  55. >>> a = Permutation(a); b = Permutation(b)
  56. >>> list(a*b)
  57. [2, 0, 1]
  58. >>> [b(a(i)) for i in range(3)]
  59. [2, 0, 1]
  60. See Also
  61. ========
  62. rmul, _af_rmul
  63. """
  64. a = abc
  65. m = len(a)
  66. if m == 3:
  67. p0, p1, p2 = a
  68. return [p0[p1[i]] for i in p2]
  69. if m == 4:
  70. p0, p1, p2, p3 = a
  71. return [p0[p1[p2[i]]] for i in p3]
  72. if m == 5:
  73. p0, p1, p2, p3, p4 = a
  74. return [p0[p1[p2[p3[i]]]] for i in p4]
  75. if m == 6:
  76. p0, p1, p2, p3, p4, p5 = a
  77. return [p0[p1[p2[p3[p4[i]]]]] for i in p5]
  78. if m == 7:
  79. p0, p1, p2, p3, p4, p5, p6 = a
  80. return [p0[p1[p2[p3[p4[p5[i]]]]]] for i in p6]
  81. if m == 8:
  82. p0, p1, p2, p3, p4, p5, p6, p7 = a
  83. return [p0[p1[p2[p3[p4[p5[p6[i]]]]]]] for i in p7]
  84. if m == 1:
  85. return a[0][:]
  86. if m == 2:
  87. a, b = a
  88. return [a[i] for i in b]
  89. if m == 0:
  90. raise ValueError("String must not be empty")
  91. p0 = _af_rmuln(*a[:m//2])
  92. p1 = _af_rmuln(*a[m//2:])
  93. return [p0[i] for i in p1]
  94. def _af_parity(pi):
  95. """
  96. Computes the parity of a permutation in array form.
  97. Explanation
  98. ===========
  99. The parity of a permutation reflects the parity of the
  100. number of inversions in the permutation, i.e., the
  101. number of pairs of x and y such that x > y but p[x] < p[y].
  102. Examples
  103. ========
  104. >>> from sympy.combinatorics.permutations import _af_parity
  105. >>> _af_parity([0, 1, 2, 3])
  106. 0
  107. >>> _af_parity([3, 2, 0, 1])
  108. 1
  109. See Also
  110. ========
  111. Permutation
  112. """
  113. n = len(pi)
  114. a = [0] * n
  115. c = 0
  116. for j in range(n):
  117. if a[j] == 0:
  118. c += 1
  119. a[j] = 1
  120. i = j
  121. while pi[i] != j:
  122. i = pi[i]
  123. a[i] = 1
  124. return (n - c) % 2
  125. def _af_invert(a):
  126. """
  127. Finds the inverse, ~A, of a permutation, A, given in array form.
  128. Examples
  129. ========
  130. >>> from sympy.combinatorics.permutations import _af_invert, _af_rmul
  131. >>> A = [1, 2, 0, 3]
  132. >>> _af_invert(A)
  133. [2, 0, 1, 3]
  134. >>> _af_rmul(_, A)
  135. [0, 1, 2, 3]
  136. See Also
  137. ========
  138. Permutation, __invert__
  139. """
  140. inv_form = [0] * len(a)
  141. for i, ai in enumerate(a):
  142. inv_form[ai] = i
  143. return inv_form
  144. def _af_pow(a, n):
  145. """
  146. Routine for finding powers of a permutation.
  147. Examples
  148. ========
  149. >>> from sympy.combinatorics import Permutation
  150. >>> from sympy.combinatorics.permutations import _af_pow
  151. >>> p = Permutation([2, 0, 3, 1])
  152. >>> p.order()
  153. 4
  154. >>> _af_pow(p._array_form, 4)
  155. [0, 1, 2, 3]
  156. """
  157. if n == 0:
  158. return list(range(len(a)))
  159. if n < 0:
  160. return _af_pow(_af_invert(a), -n)
  161. if n == 1:
  162. return a[:]
  163. elif n == 2:
  164. b = [a[i] for i in a]
  165. elif n == 3:
  166. b = [a[a[i]] for i in a]
  167. elif n == 4:
  168. b = [a[a[a[i]]] for i in a]
  169. else:
  170. # use binary multiplication
  171. b = list(range(len(a)))
  172. while 1:
  173. if n & 1:
  174. b = [b[i] for i in a]
  175. n -= 1
  176. if not n:
  177. break
  178. if n % 4 == 0:
  179. a = [a[a[a[i]]] for i in a]
  180. n = n // 4
  181. elif n % 2 == 0:
  182. a = [a[i] for i in a]
  183. n = n // 2
  184. return b
  185. def _af_commutes_with(a, b):
  186. """
  187. Checks if the two permutations with array forms
  188. given by ``a`` and ``b`` commute.
  189. Examples
  190. ========
  191. >>> from sympy.combinatorics.permutations import _af_commutes_with
  192. >>> _af_commutes_with([1, 2, 0], [0, 2, 1])
  193. False
  194. See Also
  195. ========
  196. Permutation, commutes_with
  197. """
  198. return not any(a[b[i]] != b[a[i]] for i in range(len(a) - 1))
  199. class Cycle(dict):
  200. """
  201. Wrapper around dict which provides the functionality of a disjoint cycle.
  202. Explanation
  203. ===========
  204. A cycle shows the rule to use to move subsets of elements to obtain
  205. a permutation. The Cycle class is more flexible than Permutation in
  206. that 1) all elements need not be present in order to investigate how
  207. multiple cycles act in sequence and 2) it can contain singletons:
  208. >>> from sympy.combinatorics.permutations import Perm, Cycle
  209. A Cycle will automatically parse a cycle given as a tuple on the rhs:
  210. >>> Cycle(1, 2)(2, 3)
  211. (1 3 2)
  212. The identity cycle, Cycle(), can be used to start a product:
  213. >>> Cycle()(1, 2)(2, 3)
  214. (1 3 2)
  215. The array form of a Cycle can be obtained by calling the list
  216. method (or passing it to the list function) and all elements from
  217. 0 will be shown:
  218. >>> a = Cycle(1, 2)
  219. >>> a.list()
  220. [0, 2, 1]
  221. >>> list(a)
  222. [0, 2, 1]
  223. If a larger (or smaller) range is desired use the list method and
  224. provide the desired size -- but the Cycle cannot be truncated to
  225. a size smaller than the largest element that is out of place:
  226. >>> b = Cycle(2, 4)(1, 2)(3, 1, 4)(1, 3)
  227. >>> b.list()
  228. [0, 2, 1, 3, 4]
  229. >>> b.list(b.size + 1)
  230. [0, 2, 1, 3, 4, 5]
  231. >>> b.list(-1)
  232. [0, 2, 1]
  233. Singletons are not shown when printing with one exception: the largest
  234. element is always shown -- as a singleton if necessary:
  235. >>> Cycle(1, 4, 10)(4, 5)
  236. (1 5 4 10)
  237. >>> Cycle(1, 2)(4)(5)(10)
  238. (1 2)(10)
  239. The array form can be used to instantiate a Permutation so other
  240. properties of the permutation can be investigated:
  241. >>> Perm(Cycle(1, 2)(3, 4).list()).transpositions()
  242. [(1, 2), (3, 4)]
  243. Notes
  244. =====
  245. The underlying structure of the Cycle is a dictionary and although
  246. the __iter__ method has been redefined to give the array form of the
  247. cycle, the underlying dictionary items are still available with the
  248. such methods as items():
  249. >>> list(Cycle(1, 2).items())
  250. [(1, 2), (2, 1)]
  251. See Also
  252. ========
  253. Permutation
  254. """
  255. def __missing__(self, arg):
  256. """Enter arg into dictionary and return arg."""
  257. return as_int(arg)
  258. def __iter__(self):
  259. yield from self.list()
  260. def __call__(self, *other):
  261. """Return product of cycles processed from R to L.
  262. Examples
  263. ========
  264. >>> from sympy.combinatorics import Cycle
  265. >>> Cycle(1, 2)(2, 3)
  266. (1 3 2)
  267. An instance of a Cycle will automatically parse list-like
  268. objects and Permutations that are on the right. It is more
  269. flexible than the Permutation in that all elements need not
  270. be present:
  271. >>> a = Cycle(1, 2)
  272. >>> a(2, 3)
  273. (1 3 2)
  274. >>> a(2, 3)(4, 5)
  275. (1 3 2)(4 5)
  276. """
  277. rv = Cycle(*other)
  278. for k, v in zip(list(self.keys()), [rv[self[k]] for k in self.keys()]):
  279. rv[k] = v
  280. return rv
  281. def list(self, size=None):
  282. """Return the cycles as an explicit list starting from 0 up
  283. to the greater of the largest value in the cycles and size.
  284. Truncation of trailing unmoved items will occur when size
  285. is less than the maximum element in the cycle; if this is
  286. desired, setting ``size=-1`` will guarantee such trimming.
  287. Examples
  288. ========
  289. >>> from sympy.combinatorics import Cycle
  290. >>> p = Cycle(2, 3)(4, 5)
  291. >>> p.list()
  292. [0, 1, 3, 2, 5, 4]
  293. >>> p.list(10)
  294. [0, 1, 3, 2, 5, 4, 6, 7, 8, 9]
  295. Passing a length too small will trim trailing, unchanged elements
  296. in the permutation:
  297. >>> Cycle(2, 4)(1, 2, 4).list(-1)
  298. [0, 2, 1]
  299. """
  300. if not self and size is None:
  301. raise ValueError('must give size for empty Cycle')
  302. if size is not None:
  303. big = max([i for i in self.keys() if self[i] != i] + [0])
  304. size = max(size, big + 1)
  305. else:
  306. size = self.size
  307. return [self[i] for i in range(size)]
  308. def __repr__(self):
  309. """We want it to print as a Cycle, not as a dict.
  310. Examples
  311. ========
  312. >>> from sympy.combinatorics import Cycle
  313. >>> Cycle(1, 2)
  314. (1 2)
  315. >>> print(_)
  316. (1 2)
  317. >>> list(Cycle(1, 2).items())
  318. [(1, 2), (2, 1)]
  319. """
  320. if not self:
  321. return 'Cycle()'
  322. cycles = Permutation(self).cyclic_form
  323. s = ''.join(str(tuple(c)) for c in cycles)
  324. big = self.size - 1
  325. if not any(i == big for c in cycles for i in c):
  326. s += '(%s)' % big
  327. return 'Cycle%s' % s
  328. def __str__(self):
  329. """We want it to be printed in a Cycle notation with no
  330. comma in-between.
  331. Examples
  332. ========
  333. >>> from sympy.combinatorics import Cycle
  334. >>> Cycle(1, 2)
  335. (1 2)
  336. >>> Cycle(1, 2, 4)(5, 6)
  337. (1 2 4)(5 6)
  338. """
  339. if not self:
  340. return '()'
  341. cycles = Permutation(self).cyclic_form
  342. s = ''.join(str(tuple(c)) for c in cycles)
  343. big = self.size - 1
  344. if not any(i == big for c in cycles for i in c):
  345. s += '(%s)' % big
  346. s = s.replace(',', '')
  347. return s
  348. def __init__(self, *args):
  349. """Load up a Cycle instance with the values for the cycle.
  350. Examples
  351. ========
  352. >>> from sympy.combinatorics import Cycle
  353. >>> Cycle(1, 2, 6)
  354. (1 2 6)
  355. """
  356. if not args:
  357. return
  358. if len(args) == 1:
  359. if isinstance(args[0], Permutation):
  360. for c in args[0].cyclic_form:
  361. self.update(self(*c))
  362. return
  363. elif isinstance(args[0], Cycle):
  364. for k, v in args[0].items():
  365. self[k] = v
  366. return
  367. args = [as_int(a) for a in args]
  368. if any(i < 0 for i in args):
  369. raise ValueError('negative integers are not allowed in a cycle.')
  370. if has_dups(args):
  371. raise ValueError('All elements must be unique in a cycle.')
  372. for i in range(-len(args), 0):
  373. self[args[i]] = args[i + 1]
  374. @property
  375. def size(self):
  376. if not self:
  377. return 0
  378. return max(self.keys()) + 1
  379. def copy(self):
  380. return Cycle(self)
  381. class Permutation(Atom):
  382. r"""
  383. A permutation, alternatively known as an 'arrangement number' or 'ordering'
  384. is an arrangement of the elements of an ordered list into a one-to-one
  385. mapping with itself. The permutation of a given arrangement is given by
  386. indicating the positions of the elements after re-arrangement [2]_. For
  387. example, if one started with elements ``[x, y, a, b]`` (in that order) and
  388. they were reordered as ``[x, y, b, a]`` then the permutation would be
  389. ``[0, 1, 3, 2]``. Notice that (in SymPy) the first element is always referred
  390. to as 0 and the permutation uses the indices of the elements in the
  391. original ordering, not the elements ``(a, b, ...)`` themselves.
  392. >>> from sympy.combinatorics import Permutation
  393. >>> from sympy import init_printing
  394. >>> init_printing(perm_cyclic=False, pretty_print=False)
  395. Permutations Notation
  396. =====================
  397. Permutations are commonly represented in disjoint cycle or array forms.
  398. Array Notation and 2-line Form
  399. ------------------------------------
  400. In the 2-line form, the elements and their final positions are shown
  401. as a matrix with 2 rows:
  402. [0 1 2 ... n-1]
  403. [p(0) p(1) p(2) ... p(n-1)]
  404. Since the first line is always ``range(n)``, where n is the size of p,
  405. it is sufficient to represent the permutation by the second line,
  406. referred to as the "array form" of the permutation. This is entered
  407. in brackets as the argument to the Permutation class:
  408. >>> p = Permutation([0, 2, 1]); p
  409. Permutation([0, 2, 1])
  410. Given i in range(p.size), the permutation maps i to i^p
  411. >>> [i^p for i in range(p.size)]
  412. [0, 2, 1]
  413. The composite of two permutations p*q means first apply p, then q, so
  414. i^(p*q) = (i^p)^q which is i^p^q according to Python precedence rules:
  415. >>> q = Permutation([2, 1, 0])
  416. >>> [i^p^q for i in range(3)]
  417. [2, 0, 1]
  418. >>> [i^(p*q) for i in range(3)]
  419. [2, 0, 1]
  420. One can use also the notation p(i) = i^p, but then the composition
  421. rule is (p*q)(i) = q(p(i)), not p(q(i)):
  422. >>> [(p*q)(i) for i in range(p.size)]
  423. [2, 0, 1]
  424. >>> [q(p(i)) for i in range(p.size)]
  425. [2, 0, 1]
  426. >>> [p(q(i)) for i in range(p.size)]
  427. [1, 2, 0]
  428. Disjoint Cycle Notation
  429. -----------------------
  430. In disjoint cycle notation, only the elements that have shifted are
  431. indicated.
  432. For example, [1, 3, 2, 0] can be represented as (0, 1, 3)(2).
  433. This can be understood from the 2 line format of the given permutation.
  434. In the 2-line form,
  435. [0 1 2 3]
  436. [1 3 2 0]
  437. The element in the 0th position is 1, so 0 -> 1. The element in the 1st
  438. position is three, so 1 -> 3. And the element in the third position is again
  439. 0, so 3 -> 0. Thus, 0 -> 1 -> 3 -> 0, and 2 -> 2. Thus, this can be represented
  440. as 2 cycles: (0, 1, 3)(2).
  441. In common notation, singular cycles are not explicitly written as they can be
  442. inferred implicitly.
  443. Only the relative ordering of elements in a cycle matter:
  444. >>> Permutation(1,2,3) == Permutation(2,3,1) == Permutation(3,1,2)
  445. True
  446. The disjoint cycle notation is convenient when representing
  447. permutations that have several cycles in them:
  448. >>> Permutation(1, 2)(3, 5) == Permutation([[1, 2], [3, 5]])
  449. True
  450. It also provides some economy in entry when computing products of
  451. permutations that are written in disjoint cycle notation:
  452. >>> Permutation(1, 2)(1, 3)(2, 3)
  453. Permutation([0, 3, 2, 1])
  454. >>> _ == Permutation([[1, 2]])*Permutation([[1, 3]])*Permutation([[2, 3]])
  455. True
  456. Caution: when the cycles have common elements between them then the order
  457. in which the permutations are applied matters. This module applies
  458. the permutations from *left to right*.
  459. >>> Permutation(1, 2)(2, 3) == Permutation([(1, 2), (2, 3)])
  460. True
  461. >>> Permutation(1, 2)(2, 3).list()
  462. [0, 3, 1, 2]
  463. In the above case, (1,2) is computed before (2,3).
  464. As 0 -> 0, 0 -> 0, element in position 0 is 0.
  465. As 1 -> 2, 2 -> 3, element in position 1 is 3.
  466. As 2 -> 1, 1 -> 1, element in position 2 is 1.
  467. As 3 -> 3, 3 -> 2, element in position 3 is 2.
  468. If the first and second elements had been
  469. swapped first, followed by the swapping of the second
  470. and third, the result would have been [0, 2, 3, 1].
  471. If, you want to apply the cycles in the conventional
  472. right to left order, call the function with arguments in reverse order
  473. as demonstrated below:
  474. >>> Permutation([(1, 2), (2, 3)][::-1]).list()
  475. [0, 2, 3, 1]
  476. Entering a singleton in a permutation is a way to indicate the size of the
  477. permutation. The ``size`` keyword can also be used.
  478. Array-form entry:
  479. >>> Permutation([[1, 2], [9]])
  480. Permutation([0, 2, 1], size=10)
  481. >>> Permutation([[1, 2]], size=10)
  482. Permutation([0, 2, 1], size=10)
  483. Cyclic-form entry:
  484. >>> Permutation(1, 2, size=10)
  485. Permutation([0, 2, 1], size=10)
  486. >>> Permutation(9)(1, 2)
  487. Permutation([0, 2, 1], size=10)
  488. Caution: no singleton containing an element larger than the largest
  489. in any previous cycle can be entered. This is an important difference
  490. in how Permutation and Cycle handle the ``__call__`` syntax. A singleton
  491. argument at the start of a Permutation performs instantiation of the
  492. Permutation and is permitted:
  493. >>> Permutation(5)
  494. Permutation([], size=6)
  495. A singleton entered after instantiation is a call to the permutation
  496. -- a function call -- and if the argument is out of range it will
  497. trigger an error. For this reason, it is better to start the cycle
  498. with the singleton:
  499. The following fails because there is no element 3:
  500. >>> Permutation(1, 2)(3)
  501. Traceback (most recent call last):
  502. ...
  503. IndexError: list index out of range
  504. This is ok: only the call to an out of range singleton is prohibited;
  505. otherwise the permutation autosizes:
  506. >>> Permutation(3)(1, 2)
  507. Permutation([0, 2, 1, 3])
  508. >>> Permutation(1, 2)(3, 4) == Permutation(3, 4)(1, 2)
  509. True
  510. Equality testing
  511. ----------------
  512. The array forms must be the same in order for permutations to be equal:
  513. >>> Permutation([1, 0, 2, 3]) == Permutation([1, 0])
  514. False
  515. Identity Permutation
  516. --------------------
  517. The identity permutation is a permutation in which no element is out of
  518. place. It can be entered in a variety of ways. All the following create
  519. an identity permutation of size 4:
  520. >>> I = Permutation([0, 1, 2, 3])
  521. >>> all(p == I for p in [
  522. ... Permutation(3),
  523. ... Permutation(range(4)),
  524. ... Permutation([], size=4),
  525. ... Permutation(size=4)])
  526. True
  527. Watch out for entering the range *inside* a set of brackets (which is
  528. cycle notation):
  529. >>> I == Permutation([range(4)])
  530. False
  531. Permutation Printing
  532. ====================
  533. There are a few things to note about how Permutations are printed.
  534. .. deprecated:: 1.6
  535. Configuring Permutation printing by setting
  536. ``Permutation.print_cyclic`` is deprecated. Users should use the
  537. ``perm_cyclic`` flag to the printers, as described below.
  538. 1) If you prefer one form (array or cycle) over another, you can set
  539. ``init_printing`` with the ``perm_cyclic`` flag.
  540. >>> from sympy import init_printing
  541. >>> p = Permutation(1, 2)(4, 5)(3, 4)
  542. >>> p
  543. Permutation([0, 2, 1, 4, 5, 3])
  544. >>> init_printing(perm_cyclic=True, pretty_print=False)
  545. >>> p
  546. (1 2)(3 4 5)
  547. 2) Regardless of the setting, a list of elements in the array for cyclic
  548. form can be obtained and either of those can be copied and supplied as
  549. the argument to Permutation:
  550. >>> p.array_form
  551. [0, 2, 1, 4, 5, 3]
  552. >>> p.cyclic_form
  553. [[1, 2], [3, 4, 5]]
  554. >>> Permutation(_) == p
  555. True
  556. 3) Printing is economical in that as little as possible is printed while
  557. retaining all information about the size of the permutation:
  558. >>> init_printing(perm_cyclic=False, pretty_print=False)
  559. >>> Permutation([1, 0, 2, 3])
  560. Permutation([1, 0, 2, 3])
  561. >>> Permutation([1, 0, 2, 3], size=20)
  562. Permutation([1, 0], size=20)
  563. >>> Permutation([1, 0, 2, 4, 3, 5, 6], size=20)
  564. Permutation([1, 0, 2, 4, 3], size=20)
  565. >>> p = Permutation([1, 0, 2, 3])
  566. >>> init_printing(perm_cyclic=True, pretty_print=False)
  567. >>> p
  568. (3)(0 1)
  569. >>> init_printing(perm_cyclic=False, pretty_print=False)
  570. The 2 was not printed but it is still there as can be seen with the
  571. array_form and size methods:
  572. >>> p.array_form
  573. [1, 0, 2, 3]
  574. >>> p.size
  575. 4
  576. Short introduction to other methods
  577. ===================================
  578. The permutation can act as a bijective function, telling what element is
  579. located at a given position
  580. >>> q = Permutation([5, 2, 3, 4, 1, 0])
  581. >>> q.array_form[1] # the hard way
  582. 2
  583. >>> q(1) # the easy way
  584. 2
  585. >>> {i: q(i) for i in range(q.size)} # showing the bijection
  586. {0: 5, 1: 2, 2: 3, 3: 4, 4: 1, 5: 0}
  587. The full cyclic form (including singletons) can be obtained:
  588. >>> p.full_cyclic_form
  589. [[0, 1], [2], [3]]
  590. Any permutation can be factored into transpositions of pairs of elements:
  591. >>> Permutation([[1, 2], [3, 4, 5]]).transpositions()
  592. [(1, 2), (3, 5), (3, 4)]
  593. >>> Permutation.rmul(*[Permutation([ti], size=6) for ti in _]).cyclic_form
  594. [[1, 2], [3, 4, 5]]
  595. The number of permutations on a set of n elements is given by n! and is
  596. called the cardinality.
  597. >>> p.size
  598. 4
  599. >>> p.cardinality
  600. 24
  601. A given permutation has a rank among all the possible permutations of the
  602. same elements, but what that rank is depends on how the permutations are
  603. enumerated. (There are a number of different methods of doing so.) The
  604. lexicographic rank is given by the rank method and this rank is used to
  605. increment a permutation with addition/subtraction:
  606. >>> p.rank()
  607. 6
  608. >>> p + 1
  609. Permutation([1, 0, 3, 2])
  610. >>> p.next_lex()
  611. Permutation([1, 0, 3, 2])
  612. >>> _.rank()
  613. 7
  614. >>> p.unrank_lex(p.size, rank=7)
  615. Permutation([1, 0, 3, 2])
  616. The product of two permutations p and q is defined as their composition as
  617. functions, (p*q)(i) = q(p(i)) [6]_.
  618. >>> p = Permutation([1, 0, 2, 3])
  619. >>> q = Permutation([2, 3, 1, 0])
  620. >>> list(q*p)
  621. [2, 3, 0, 1]
  622. >>> list(p*q)
  623. [3, 2, 1, 0]
  624. >>> [q(p(i)) for i in range(p.size)]
  625. [3, 2, 1, 0]
  626. The permutation can be 'applied' to any list-like object, not only
  627. Permutations:
  628. >>> p(['zero', 'one', 'four', 'two'])
  629. ['one', 'zero', 'four', 'two']
  630. >>> p('zo42')
  631. ['o', 'z', '4', '2']
  632. If you have a list of arbitrary elements, the corresponding permutation
  633. can be found with the from_sequence method:
  634. >>> Permutation.from_sequence('SymPy')
  635. Permutation([1, 3, 2, 0, 4])
  636. Checking if a Permutation is contained in a Group
  637. =================================================
  638. Generally if you have a group of permutations G on n symbols, and
  639. you're checking if a permutation on less than n symbols is part
  640. of that group, the check will fail.
  641. Here is an example for n=5 and we check if the cycle
  642. (1,2,3) is in G:
  643. >>> from sympy import init_printing
  644. >>> init_printing(perm_cyclic=True, pretty_print=False)
  645. >>> from sympy.combinatorics import Cycle, Permutation
  646. >>> from sympy.combinatorics.perm_groups import PermutationGroup
  647. >>> G = PermutationGroup(Cycle(2, 3)(4, 5), Cycle(1, 2, 3, 4, 5))
  648. >>> p1 = Permutation(Cycle(2, 5, 3))
  649. >>> p2 = Permutation(Cycle(1, 2, 3))
  650. >>> a1 = Permutation(Cycle(1, 2, 3).list(6))
  651. >>> a2 = Permutation(Cycle(1, 2, 3)(5))
  652. >>> a3 = Permutation(Cycle(1, 2, 3),size=6)
  653. >>> for p in [p1,p2,a1,a2,a3]: p, G.contains(p)
  654. ((2 5 3), True)
  655. ((1 2 3), False)
  656. ((5)(1 2 3), True)
  657. ((5)(1 2 3), True)
  658. ((5)(1 2 3), True)
  659. The check for p2 above will fail.
  660. Checking if p1 is in G works because SymPy knows
  661. G is a group on 5 symbols, and p1 is also on 5 symbols
  662. (its largest element is 5).
  663. For ``a1``, the ``.list(6)`` call will extend the permutation to 5
  664. symbols, so the test will work as well. In the case of ``a2`` the
  665. permutation is being extended to 5 symbols by using a singleton,
  666. and in the case of ``a3`` it's extended through the constructor
  667. argument ``size=6``.
  668. There is another way to do this, which is to tell the ``contains``
  669. method that the number of symbols the group is on does not need to
  670. match perfectly the number of symbols for the permutation:
  671. >>> G.contains(p2,strict=False)
  672. True
  673. This can be via the ``strict`` argument to the ``contains`` method,
  674. and SymPy will try to extend the permutation on its own and then
  675. perform the containment check.
  676. See Also
  677. ========
  678. Cycle
  679. References
  680. ==========
  681. .. [1] Skiena, S. 'Permutations.' 1.1 in Implementing Discrete Mathematics
  682. Combinatorics and Graph Theory with Mathematica. Reading, MA:
  683. Addison-Wesley, pp. 3-16, 1990.
  684. .. [2] Knuth, D. E. The Art of Computer Programming, Vol. 4: Combinatorial
  685. Algorithms, 1st ed. Reading, MA: Addison-Wesley, 2011.
  686. .. [3] Wendy Myrvold and Frank Ruskey. 2001. Ranking and unranking
  687. permutations in linear time. Inf. Process. Lett. 79, 6 (September 2001),
  688. 281-284. DOI=10.1016/S0020-0190(01)00141-7
  689. .. [4] D. L. Kreher, D. R. Stinson 'Combinatorial Algorithms'
  690. CRC Press, 1999
  691. .. [5] Graham, R. L.; Knuth, D. E.; and Patashnik, O.
  692. Concrete Mathematics: A Foundation for Computer Science, 2nd ed.
  693. Reading, MA: Addison-Wesley, 1994.
  694. .. [6] https://en.wikipedia.org/w/index.php?oldid=499948155#Product_and_inverse
  695. .. [7] https://en.wikipedia.org/wiki/Lehmer_code
  696. """
  697. is_Permutation = True
  698. _array_form = None
  699. _cyclic_form = None
  700. _cycle_structure = None
  701. _size = None
  702. _rank = None
  703. def __new__(cls, *args, size=None, **kwargs):
  704. """
  705. Constructor for the Permutation object from a list or a
  706. list of lists in which all elements of the permutation may
  707. appear only once.
  708. Examples
  709. ========
  710. >>> from sympy.combinatorics import Permutation
  711. >>> from sympy import init_printing
  712. >>> init_printing(perm_cyclic=False, pretty_print=False)
  713. Permutations entered in array-form are left unaltered:
  714. >>> Permutation([0, 2, 1])
  715. Permutation([0, 2, 1])
  716. Permutations entered in cyclic form are converted to array form;
  717. singletons need not be entered, but can be entered to indicate the
  718. largest element:
  719. >>> Permutation([[4, 5, 6], [0, 1]])
  720. Permutation([1, 0, 2, 3, 5, 6, 4])
  721. >>> Permutation([[4, 5, 6], [0, 1], [19]])
  722. Permutation([1, 0, 2, 3, 5, 6, 4], size=20)
  723. All manipulation of permutations assumes that the smallest element
  724. is 0 (in keeping with 0-based indexing in Python) so if the 0 is
  725. missing when entering a permutation in array form, an error will be
  726. raised:
  727. >>> Permutation([2, 1])
  728. Traceback (most recent call last):
  729. ...
  730. ValueError: Integers 0 through 2 must be present.
  731. If a permutation is entered in cyclic form, it can be entered without
  732. singletons and the ``size`` specified so those values can be filled
  733. in, otherwise the array form will only extend to the maximum value
  734. in the cycles:
  735. >>> Permutation([[1, 4], [3, 5, 2]], size=10)
  736. Permutation([0, 4, 3, 5, 1, 2], size=10)
  737. >>> _.array_form
  738. [0, 4, 3, 5, 1, 2, 6, 7, 8, 9]
  739. """
  740. if size is not None:
  741. size = int(size)
  742. #a) ()
  743. #b) (1) = identity
  744. #c) (1, 2) = cycle
  745. #d) ([1, 2, 3]) = array form
  746. #e) ([[1, 2]]) = cyclic form
  747. #f) (Cycle) = conversion to permutation
  748. #g) (Permutation) = adjust size or return copy
  749. ok = True
  750. if not args: # a
  751. return cls._af_new(list(range(size or 0)))
  752. elif len(args) > 1: # c
  753. return cls._af_new(Cycle(*args).list(size))
  754. if len(args) == 1:
  755. a = args[0]
  756. if isinstance(a, cls): # g
  757. if size is None or size == a.size:
  758. return a
  759. return cls(a.array_form, size=size)
  760. if isinstance(a, Cycle): # f
  761. return cls._af_new(a.list(size))
  762. if not is_sequence(a): # b
  763. if size is not None and a + 1 > size:
  764. raise ValueError('size is too small when max is %s' % a)
  765. return cls._af_new(list(range(a + 1)))
  766. if has_variety(is_sequence(ai) for ai in a):
  767. ok = False
  768. else:
  769. ok = False
  770. if not ok:
  771. raise ValueError("Permutation argument must be a list of ints, "
  772. "a list of lists, Permutation or Cycle.")
  773. # safe to assume args are valid; this also makes a copy
  774. # of the args
  775. args = list(args[0])
  776. is_cycle = args and is_sequence(args[0])
  777. if is_cycle: # e
  778. args = [[int(i) for i in c] for c in args]
  779. else: # d
  780. args = [int(i) for i in args]
  781. # if there are n elements present, 0, 1, ..., n-1 should be present
  782. # unless a cycle notation has been provided. A 0 will be added
  783. # for convenience in case one wants to enter permutations where
  784. # counting starts from 1.
  785. temp = flatten(args)
  786. if has_dups(temp) and not is_cycle:
  787. raise ValueError('there were repeated elements.')
  788. temp = set(temp)
  789. if not is_cycle:
  790. if temp != set(range(len(temp))):
  791. raise ValueError('Integers 0 through %s must be present.' %
  792. max(temp))
  793. if size is not None and temp and max(temp) + 1 > size:
  794. raise ValueError('max element should not exceed %s' % (size - 1))
  795. if is_cycle:
  796. # it's not necessarily canonical so we won't store
  797. # it -- use the array form instead
  798. c = Cycle()
  799. for ci in args:
  800. c = c(*ci)
  801. aform = c.list()
  802. else:
  803. aform = list(args)
  804. if size and size > len(aform):
  805. # don't allow for truncation of permutation which
  806. # might split a cycle and lead to an invalid aform
  807. # but do allow the permutation size to be increased
  808. aform.extend(list(range(len(aform), size)))
  809. return cls._af_new(aform)
  810. @classmethod
  811. def _af_new(cls, perm):
  812. """A method to produce a Permutation object from a list;
  813. the list is bound to the _array_form attribute, so it must
  814. not be modified; this method is meant for internal use only;
  815. the list ``a`` is supposed to be generated as a temporary value
  816. in a method, so p = Perm._af_new(a) is the only object
  817. to hold a reference to ``a``::
  818. Examples
  819. ========
  820. >>> from sympy.combinatorics.permutations import Perm
  821. >>> from sympy import init_printing
  822. >>> init_printing(perm_cyclic=False, pretty_print=False)
  823. >>> a = [2, 1, 3, 0]
  824. >>> p = Perm._af_new(a)
  825. >>> p
  826. Permutation([2, 1, 3, 0])
  827. """
  828. p = super().__new__(cls)
  829. p._array_form = perm
  830. p._size = len(perm)
  831. return p
  832. def _hashable_content(self):
  833. # the array_form (a list) is the Permutation arg, so we need to
  834. # return a tuple, instead
  835. return tuple(self.array_form)
  836. @property
  837. def array_form(self):
  838. """
  839. Return a copy of the attribute _array_form
  840. Examples
  841. ========
  842. >>> from sympy.combinatorics import Permutation
  843. >>> p = Permutation([[2, 0], [3, 1]])
  844. >>> p.array_form
  845. [2, 3, 0, 1]
  846. >>> Permutation([[2, 0, 3, 1]]).array_form
  847. [3, 2, 0, 1]
  848. >>> Permutation([2, 0, 3, 1]).array_form
  849. [2, 0, 3, 1]
  850. >>> Permutation([[1, 2], [4, 5]]).array_form
  851. [0, 2, 1, 3, 5, 4]
  852. """
  853. return self._array_form[:]
  854. def list(self, size=None):
  855. """Return the permutation as an explicit list, possibly
  856. trimming unmoved elements if size is less than the maximum
  857. element in the permutation; if this is desired, setting
  858. ``size=-1`` will guarantee such trimming.
  859. Examples
  860. ========
  861. >>> from sympy.combinatorics import Permutation
  862. >>> p = Permutation(2, 3)(4, 5)
  863. >>> p.list()
  864. [0, 1, 3, 2, 5, 4]
  865. >>> p.list(10)
  866. [0, 1, 3, 2, 5, 4, 6, 7, 8, 9]
  867. Passing a length too small will trim trailing, unchanged elements
  868. in the permutation:
  869. >>> Permutation(2, 4)(1, 2, 4).list(-1)
  870. [0, 2, 1]
  871. >>> Permutation(3).list(-1)
  872. []
  873. """
  874. if not self and size is None:
  875. raise ValueError('must give size for empty Cycle')
  876. rv = self.array_form
  877. if size is not None:
  878. if size > self.size:
  879. rv.extend(list(range(self.size, size)))
  880. else:
  881. # find first value from rhs where rv[i] != i
  882. i = self.size - 1
  883. while rv:
  884. if rv[-1] != i:
  885. break
  886. rv.pop()
  887. i -= 1
  888. return rv
  889. @property
  890. def cyclic_form(self):
  891. """
  892. This is used to convert to the cyclic notation
  893. from the canonical notation. Singletons are omitted.
  894. Examples
  895. ========
  896. >>> from sympy.combinatorics import Permutation
  897. >>> p = Permutation([0, 3, 1, 2])
  898. >>> p.cyclic_form
  899. [[1, 3, 2]]
  900. >>> Permutation([1, 0, 2, 4, 3, 5]).cyclic_form
  901. [[0, 1], [3, 4]]
  902. See Also
  903. ========
  904. array_form, full_cyclic_form
  905. """
  906. if self._cyclic_form is not None:
  907. return list(self._cyclic_form)
  908. array_form = self.array_form
  909. unchecked = [True] * len(array_form)
  910. cyclic_form = []
  911. for i in range(len(array_form)):
  912. if unchecked[i]:
  913. cycle = []
  914. cycle.append(i)
  915. unchecked[i] = False
  916. j = i
  917. while unchecked[array_form[j]]:
  918. j = array_form[j]
  919. cycle.append(j)
  920. unchecked[j] = False
  921. if len(cycle) > 1:
  922. cyclic_form.append(cycle)
  923. assert cycle == list(minlex(cycle))
  924. cyclic_form.sort()
  925. self._cyclic_form = cyclic_form[:]
  926. return cyclic_form
  927. @property
  928. def full_cyclic_form(self):
  929. """Return permutation in cyclic form including singletons.
  930. Examples
  931. ========
  932. >>> from sympy.combinatorics import Permutation
  933. >>> Permutation([0, 2, 1]).full_cyclic_form
  934. [[0], [1, 2]]
  935. """
  936. need = set(range(self.size)) - set(flatten(self.cyclic_form))
  937. rv = self.cyclic_form + [[i] for i in need]
  938. rv.sort()
  939. return rv
  940. @property
  941. def size(self):
  942. """
  943. Returns the number of elements in the permutation.
  944. Examples
  945. ========
  946. >>> from sympy.combinatorics import Permutation
  947. >>> Permutation([[3, 2], [0, 1]]).size
  948. 4
  949. See Also
  950. ========
  951. cardinality, length, order, rank
  952. """
  953. return self._size
  954. def support(self):
  955. """Return the elements in permutation, P, for which P[i] != i.
  956. Examples
  957. ========
  958. >>> from sympy.combinatorics import Permutation
  959. >>> p = Permutation([[3, 2], [0, 1], [4]])
  960. >>> p.array_form
  961. [1, 0, 3, 2, 4]
  962. >>> p.support()
  963. [0, 1, 2, 3]
  964. """
  965. a = self.array_form
  966. return [i for i, e in enumerate(a) if a[i] != i]
  967. def __add__(self, other):
  968. """Return permutation that is other higher in rank than self.
  969. The rank is the lexicographical rank, with the identity permutation
  970. having rank of 0.
  971. Examples
  972. ========
  973. >>> from sympy.combinatorics import Permutation
  974. >>> I = Permutation([0, 1, 2, 3])
  975. >>> a = Permutation([2, 1, 3, 0])
  976. >>> I + a.rank() == a
  977. True
  978. See Also
  979. ========
  980. __sub__, inversion_vector
  981. """
  982. rank = (self.rank() + other) % self.cardinality
  983. rv = self.unrank_lex(self.size, rank)
  984. rv._rank = rank
  985. return rv
  986. def __sub__(self, other):
  987. """Return the permutation that is other lower in rank than self.
  988. See Also
  989. ========
  990. __add__
  991. """
  992. return self.__add__(-other)
  993. @staticmethod
  994. def rmul(*args):
  995. """
  996. Return product of Permutations [a, b, c, ...] as the Permutation whose
  997. ith value is a(b(c(i))).
  998. a, b, c, ... can be Permutation objects or tuples.
  999. Examples
  1000. ========
  1001. >>> from sympy.combinatorics import Permutation
  1002. >>> a, b = [1, 0, 2], [0, 2, 1]
  1003. >>> a = Permutation(a); b = Permutation(b)
  1004. >>> list(Permutation.rmul(a, b))
  1005. [1, 2, 0]
  1006. >>> [a(b(i)) for i in range(3)]
  1007. [1, 2, 0]
  1008. This handles the operands in reverse order compared to the ``*`` operator:
  1009. >>> a = Permutation(a); b = Permutation(b)
  1010. >>> list(a*b)
  1011. [2, 0, 1]
  1012. >>> [b(a(i)) for i in range(3)]
  1013. [2, 0, 1]
  1014. Notes
  1015. =====
  1016. All items in the sequence will be parsed by Permutation as
  1017. necessary as long as the first item is a Permutation:
  1018. >>> Permutation.rmul(a, [0, 2, 1]) == Permutation.rmul(a, b)
  1019. True
  1020. The reverse order of arguments will raise a TypeError.
  1021. """
  1022. rv = args[0]
  1023. for i in range(1, len(args)):
  1024. rv = args[i]*rv
  1025. return rv
  1026. @classmethod
  1027. def rmul_with_af(cls, *args):
  1028. """
  1029. same as rmul, but the elements of args are Permutation objects
  1030. which have _array_form
  1031. """
  1032. a = [x._array_form for x in args]
  1033. rv = cls._af_new(_af_rmuln(*a))
  1034. return rv
  1035. def mul_inv(self, other):
  1036. """
  1037. other*~self, self and other have _array_form
  1038. """
  1039. a = _af_invert(self._array_form)
  1040. b = other._array_form
  1041. return self._af_new(_af_rmul(a, b))
  1042. def __rmul__(self, other):
  1043. """This is needed to coerce other to Permutation in rmul."""
  1044. cls = type(self)
  1045. return cls(other)*self
  1046. def __mul__(self, other):
  1047. """
  1048. Return the product a*b as a Permutation; the ith value is b(a(i)).
  1049. Examples
  1050. ========
  1051. >>> from sympy.combinatorics.permutations import _af_rmul, Permutation
  1052. >>> a, b = [1, 0, 2], [0, 2, 1]
  1053. >>> a = Permutation(a); b = Permutation(b)
  1054. >>> list(a*b)
  1055. [2, 0, 1]
  1056. >>> [b(a(i)) for i in range(3)]
  1057. [2, 0, 1]
  1058. This handles operands in reverse order compared to _af_rmul and rmul:
  1059. >>> al = list(a); bl = list(b)
  1060. >>> _af_rmul(al, bl)
  1061. [1, 2, 0]
  1062. >>> [al[bl[i]] for i in range(3)]
  1063. [1, 2, 0]
  1064. It is acceptable for the arrays to have different lengths; the shorter
  1065. one will be padded to match the longer one:
  1066. >>> from sympy import init_printing
  1067. >>> init_printing(perm_cyclic=False, pretty_print=False)
  1068. >>> b*Permutation([1, 0])
  1069. Permutation([1, 2, 0])
  1070. >>> Permutation([1, 0])*b
  1071. Permutation([2, 0, 1])
  1072. It is also acceptable to allow coercion to handle conversion of a
  1073. single list to the left of a Permutation:
  1074. >>> [0, 1]*a # no change: 2-element identity
  1075. Permutation([1, 0, 2])
  1076. >>> [[0, 1]]*a # exchange first two elements
  1077. Permutation([0, 1, 2])
  1078. You cannot use more than 1 cycle notation in a product of cycles
  1079. since coercion can only handle one argument to the left. To handle
  1080. multiple cycles it is convenient to use Cycle instead of Permutation:
  1081. >>> [[1, 2]]*[[2, 3]]*Permutation([]) # doctest: +SKIP
  1082. >>> from sympy.combinatorics.permutations import Cycle
  1083. >>> Cycle(1, 2)(2, 3)
  1084. (1 3 2)
  1085. """
  1086. from sympy.combinatorics.perm_groups import PermutationGroup, Coset
  1087. if isinstance(other, PermutationGroup):
  1088. return Coset(self, other, dir='-')
  1089. a = self.array_form
  1090. # __rmul__ makes sure the other is a Permutation
  1091. b = other.array_form
  1092. if not b:
  1093. perm = a
  1094. else:
  1095. b.extend(list(range(len(b), len(a))))
  1096. perm = [b[i] for i in a] + b[len(a):]
  1097. return self._af_new(perm)
  1098. def commutes_with(self, other):
  1099. """
  1100. Checks if the elements are commuting.
  1101. Examples
  1102. ========
  1103. >>> from sympy.combinatorics import Permutation
  1104. >>> a = Permutation([1, 4, 3, 0, 2, 5])
  1105. >>> b = Permutation([0, 1, 2, 3, 4, 5])
  1106. >>> a.commutes_with(b)
  1107. True
  1108. >>> b = Permutation([2, 3, 5, 4, 1, 0])
  1109. >>> a.commutes_with(b)
  1110. False
  1111. """
  1112. a = self.array_form
  1113. b = other.array_form
  1114. return _af_commutes_with(a, b)
  1115. def __pow__(self, n):
  1116. """
  1117. Routine for finding powers of a permutation.
  1118. Examples
  1119. ========
  1120. >>> from sympy.combinatorics import Permutation
  1121. >>> from sympy import init_printing
  1122. >>> init_printing(perm_cyclic=False, pretty_print=False)
  1123. >>> p = Permutation([2, 0, 3, 1])
  1124. >>> p.order()
  1125. 4
  1126. >>> p**4
  1127. Permutation([0, 1, 2, 3])
  1128. """
  1129. if isinstance(n, Permutation):
  1130. raise NotImplementedError(
  1131. 'p**p is not defined; do you mean p^p (conjugate)?')
  1132. n = int(n)
  1133. return self._af_new(_af_pow(self.array_form, n))
  1134. def __rxor__(self, i):
  1135. """Return self(i) when ``i`` is an int.
  1136. Examples
  1137. ========
  1138. >>> from sympy.combinatorics import Permutation
  1139. >>> p = Permutation(1, 2, 9)
  1140. >>> 2^p == p(2) == 9
  1141. True
  1142. """
  1143. if int(i) == i:
  1144. return self(i)
  1145. else:
  1146. raise NotImplementedError(
  1147. "i^p = p(i) when i is an integer, not %s." % i)
  1148. def __xor__(self, h):
  1149. """Return the conjugate permutation ``~h*self*h` `.
  1150. Explanation
  1151. ===========
  1152. If ``a`` and ``b`` are conjugates, ``a = h*b*~h`` and
  1153. ``b = ~h*a*h`` and both have the same cycle structure.
  1154. Examples
  1155. ========
  1156. >>> from sympy.combinatorics import Permutation
  1157. >>> p = Permutation(1, 2, 9)
  1158. >>> q = Permutation(6, 9, 8)
  1159. >>> p*q != q*p
  1160. True
  1161. Calculate and check properties of the conjugate:
  1162. >>> c = p^q
  1163. >>> c == ~q*p*q and p == q*c*~q
  1164. True
  1165. The expression q^p^r is equivalent to q^(p*r):
  1166. >>> r = Permutation(9)(4, 6, 8)
  1167. >>> q^p^r == q^(p*r)
  1168. True
  1169. If the term to the left of the conjugate operator, i, is an integer
  1170. then this is interpreted as selecting the ith element from the
  1171. permutation to the right:
  1172. >>> all(i^p == p(i) for i in range(p.size))
  1173. True
  1174. Note that the * operator as higher precedence than the ^ operator:
  1175. >>> q^r*p^r == q^(r*p)^r == Permutation(9)(1, 6, 4)
  1176. True
  1177. Notes
  1178. =====
  1179. In Python the precedence rule is p^q^r = (p^q)^r which differs
  1180. in general from p^(q^r)
  1181. >>> q^p^r
  1182. (9)(1 4 8)
  1183. >>> q^(p^r)
  1184. (9)(1 8 6)
  1185. For a given r and p, both of the following are conjugates of p:
  1186. ~r*p*r and r*p*~r. But these are not necessarily the same:
  1187. >>> ~r*p*r == r*p*~r
  1188. True
  1189. >>> p = Permutation(1, 2, 9)(5, 6)
  1190. >>> ~r*p*r == r*p*~r
  1191. False
  1192. The conjugate ~r*p*r was chosen so that ``p^q^r`` would be equivalent
  1193. to ``p^(q*r)`` rather than ``p^(r*q)``. To obtain r*p*~r, pass ~r to
  1194. this method:
  1195. >>> p^~r == r*p*~r
  1196. True
  1197. """
  1198. if self.size != h.size:
  1199. raise ValueError("The permutations must be of equal size.")
  1200. a = [None]*self.size
  1201. h = h._array_form
  1202. p = self._array_form
  1203. for i in range(self.size):
  1204. a[h[i]] = h[p[i]]
  1205. return self._af_new(a)
  1206. def transpositions(self):
  1207. """
  1208. Return the permutation decomposed into a list of transpositions.
  1209. Explanation
  1210. ===========
  1211. It is always possible to express a permutation as the product of
  1212. transpositions, see [1]
  1213. Examples
  1214. ========
  1215. >>> from sympy.combinatorics import Permutation
  1216. >>> p = Permutation([[1, 2, 3], [0, 4, 5, 6, 7]])
  1217. >>> t = p.transpositions()
  1218. >>> t
  1219. [(0, 7), (0, 6), (0, 5), (0, 4), (1, 3), (1, 2)]
  1220. >>> print(''.join(str(c) for c in t))
  1221. (0, 7)(0, 6)(0, 5)(0, 4)(1, 3)(1, 2)
  1222. >>> Permutation.rmul(*[Permutation([ti], size=p.size) for ti in t]) == p
  1223. True
  1224. References
  1225. ==========
  1226. .. [1] https://en.wikipedia.org/wiki/Transposition_%28mathematics%29#Properties
  1227. """
  1228. a = self.cyclic_form
  1229. res = []
  1230. for x in a:
  1231. nx = len(x)
  1232. if nx == 2:
  1233. res.append(tuple(x))
  1234. elif nx > 2:
  1235. first = x[0]
  1236. for y in x[nx - 1:0:-1]:
  1237. res.append((first, y))
  1238. return res
  1239. @classmethod
  1240. def from_sequence(self, i, key=None):
  1241. """Return the permutation needed to obtain ``i`` from the sorted
  1242. elements of ``i``. If custom sorting is desired, a key can be given.
  1243. Examples
  1244. ========
  1245. >>> from sympy.combinatorics import Permutation
  1246. >>> Permutation.from_sequence('SymPy')
  1247. (4)(0 1 3)
  1248. >>> _(sorted("SymPy"))
  1249. ['S', 'y', 'm', 'P', 'y']
  1250. >>> Permutation.from_sequence('SymPy', key=lambda x: x.lower())
  1251. (4)(0 2)(1 3)
  1252. """
  1253. ic = list(zip(i, list(range(len(i)))))
  1254. if key:
  1255. ic.sort(key=lambda x: key(x[0]))
  1256. else:
  1257. ic.sort()
  1258. return ~Permutation([i[1] for i in ic])
  1259. def __invert__(self):
  1260. """
  1261. Return the inverse of the permutation.
  1262. A permutation multiplied by its inverse is the identity permutation.
  1263. Examples
  1264. ========
  1265. >>> from sympy.combinatorics import Permutation
  1266. >>> from sympy import init_printing
  1267. >>> init_printing(perm_cyclic=False, pretty_print=False)
  1268. >>> p = Permutation([[2, 0], [3, 1]])
  1269. >>> ~p
  1270. Permutation([2, 3, 0, 1])
  1271. >>> _ == p**-1
  1272. True
  1273. >>> p*~p == ~p*p == Permutation([0, 1, 2, 3])
  1274. True
  1275. """
  1276. return self._af_new(_af_invert(self._array_form))
  1277. def __iter__(self):
  1278. """Yield elements from array form.
  1279. Examples
  1280. ========
  1281. >>> from sympy.combinatorics import Permutation
  1282. >>> list(Permutation(range(3)))
  1283. [0, 1, 2]
  1284. """
  1285. yield from self.array_form
  1286. def __repr__(self):
  1287. return srepr(self)
  1288. def __call__(self, *i):
  1289. """
  1290. Allows applying a permutation instance as a bijective function.
  1291. Examples
  1292. ========
  1293. >>> from sympy.combinatorics import Permutation
  1294. >>> p = Permutation([[2, 0], [3, 1]])
  1295. >>> p.array_form
  1296. [2, 3, 0, 1]
  1297. >>> [p(i) for i in range(4)]
  1298. [2, 3, 0, 1]
  1299. If an array is given then the permutation selects the items
  1300. from the array (i.e. the permutation is applied to the array):
  1301. >>> from sympy.abc import x
  1302. >>> p([x, 1, 0, x**2])
  1303. [0, x**2, x, 1]
  1304. """
  1305. # list indices can be Integer or int; leave this
  1306. # as it is (don't test or convert it) because this
  1307. # gets called a lot and should be fast
  1308. if len(i) == 1:
  1309. i = i[0]
  1310. if not isinstance(i, Iterable):
  1311. i = as_int(i)
  1312. if i < 0 or i > self.size:
  1313. raise TypeError(
  1314. "{} should be an integer between 0 and {}"
  1315. .format(i, self.size-1))
  1316. return self._array_form[i]
  1317. # P([a, b, c])
  1318. if len(i) != self.size:
  1319. raise TypeError(
  1320. "{} should have the length {}.".format(i, self.size))
  1321. return [i[j] for j in self._array_form]
  1322. # P(1, 2, 3)
  1323. return self*Permutation(Cycle(*i), size=self.size)
  1324. def atoms(self):
  1325. """
  1326. Returns all the elements of a permutation
  1327. Examples
  1328. ========
  1329. >>> from sympy.combinatorics import Permutation
  1330. >>> Permutation([0, 1, 2, 3, 4, 5]).atoms()
  1331. {0, 1, 2, 3, 4, 5}
  1332. >>> Permutation([[0, 1], [2, 3], [4, 5]]).atoms()
  1333. {0, 1, 2, 3, 4, 5}
  1334. """
  1335. return set(self.array_form)
  1336. def apply(self, i):
  1337. r"""Apply the permutation to an expression.
  1338. Parameters
  1339. ==========
  1340. i : Expr
  1341. It should be an integer between $0$ and $n-1$ where $n$
  1342. is the size of the permutation.
  1343. If it is a symbol or a symbolic expression that can
  1344. have integer values, an ``AppliedPermutation`` object
  1345. will be returned which can represent an unevaluated
  1346. function.
  1347. Notes
  1348. =====
  1349. Any permutation can be defined as a bijective function
  1350. $\sigma : \{ 0, 1, \dots, n-1 \} \rightarrow \{ 0, 1, \dots, n-1 \}$
  1351. where $n$ denotes the size of the permutation.
  1352. The definition may even be extended for any set with distinctive
  1353. elements, such that the permutation can even be applied for
  1354. real numbers or such, however, it is not implemented for now for
  1355. computational reasons and the integrity with the group theory
  1356. module.
  1357. This function is similar to the ``__call__`` magic, however,
  1358. ``__call__`` magic already has some other applications like
  1359. permuting an array or attaching new cycles, which would
  1360. not always be mathematically consistent.
  1361. This also guarantees that the return type is a SymPy integer,
  1362. which guarantees the safety to use assumptions.
  1363. """
  1364. i = _sympify(i)
  1365. if i.is_integer is False:
  1366. raise NotImplementedError("{} should be an integer.".format(i))
  1367. n = self.size
  1368. if (i < 0) == True or (i >= n) == True:
  1369. raise NotImplementedError(
  1370. "{} should be an integer between 0 and {}".format(i, n-1))
  1371. if i.is_Integer:
  1372. return Integer(self._array_form[i])
  1373. return AppliedPermutation(self, i)
  1374. def next_lex(self):
  1375. """
  1376. Returns the next permutation in lexicographical order.
  1377. If self is the last permutation in lexicographical order
  1378. it returns None.
  1379. See [4] section 2.4.
  1380. Examples
  1381. ========
  1382. >>> from sympy.combinatorics import Permutation
  1383. >>> p = Permutation([2, 3, 1, 0])
  1384. >>> p = Permutation([2, 3, 1, 0]); p.rank()
  1385. 17
  1386. >>> p = p.next_lex(); p.rank()
  1387. 18
  1388. See Also
  1389. ========
  1390. rank, unrank_lex
  1391. """
  1392. perm = self.array_form[:]
  1393. n = len(perm)
  1394. i = n - 2
  1395. while perm[i + 1] < perm[i]:
  1396. i -= 1
  1397. if i == -1:
  1398. return None
  1399. else:
  1400. j = n - 1
  1401. while perm[j] < perm[i]:
  1402. j -= 1
  1403. perm[j], perm[i] = perm[i], perm[j]
  1404. i += 1
  1405. j = n - 1
  1406. while i < j:
  1407. perm[j], perm[i] = perm[i], perm[j]
  1408. i += 1
  1409. j -= 1
  1410. return self._af_new(perm)
  1411. @classmethod
  1412. def unrank_nonlex(self, n, r):
  1413. """
  1414. This is a linear time unranking algorithm that does not
  1415. respect lexicographic order [3].
  1416. Examples
  1417. ========
  1418. >>> from sympy.combinatorics import Permutation
  1419. >>> from sympy import init_printing
  1420. >>> init_printing(perm_cyclic=False, pretty_print=False)
  1421. >>> Permutation.unrank_nonlex(4, 5)
  1422. Permutation([2, 0, 3, 1])
  1423. >>> Permutation.unrank_nonlex(4, -1)
  1424. Permutation([0, 1, 2, 3])
  1425. See Also
  1426. ========
  1427. next_nonlex, rank_nonlex
  1428. """
  1429. def _unrank1(n, r, a):
  1430. if n > 0:
  1431. a[n - 1], a[r % n] = a[r % n], a[n - 1]
  1432. _unrank1(n - 1, r//n, a)
  1433. id_perm = list(range(n))
  1434. n = int(n)
  1435. r = r % ifac(n)
  1436. _unrank1(n, r, id_perm)
  1437. return self._af_new(id_perm)
  1438. def rank_nonlex(self, inv_perm=None):
  1439. """
  1440. This is a linear time ranking algorithm that does not
  1441. enforce lexicographic order [3].
  1442. Examples
  1443. ========
  1444. >>> from sympy.combinatorics import Permutation
  1445. >>> p = Permutation([0, 1, 2, 3])
  1446. >>> p.rank_nonlex()
  1447. 23
  1448. See Also
  1449. ========
  1450. next_nonlex, unrank_nonlex
  1451. """
  1452. def _rank1(n, perm, inv_perm):
  1453. if n == 1:
  1454. return 0
  1455. s = perm[n - 1]
  1456. t = inv_perm[n - 1]
  1457. perm[n - 1], perm[t] = perm[t], s
  1458. inv_perm[n - 1], inv_perm[s] = inv_perm[s], t
  1459. return s + n*_rank1(n - 1, perm, inv_perm)
  1460. if inv_perm is None:
  1461. inv_perm = (~self).array_form
  1462. if not inv_perm:
  1463. return 0
  1464. perm = self.array_form[:]
  1465. r = _rank1(len(perm), perm, inv_perm)
  1466. return r
  1467. def next_nonlex(self):
  1468. """
  1469. Returns the next permutation in nonlex order [3].
  1470. If self is the last permutation in this order it returns None.
  1471. Examples
  1472. ========
  1473. >>> from sympy.combinatorics import Permutation
  1474. >>> from sympy import init_printing
  1475. >>> init_printing(perm_cyclic=False, pretty_print=False)
  1476. >>> p = Permutation([2, 0, 3, 1]); p.rank_nonlex()
  1477. 5
  1478. >>> p = p.next_nonlex(); p
  1479. Permutation([3, 0, 1, 2])
  1480. >>> p.rank_nonlex()
  1481. 6
  1482. See Also
  1483. ========
  1484. rank_nonlex, unrank_nonlex
  1485. """
  1486. r = self.rank_nonlex()
  1487. if r == ifac(self.size) - 1:
  1488. return None
  1489. return self.unrank_nonlex(self.size, r + 1)
  1490. def rank(self):
  1491. """
  1492. Returns the lexicographic rank of the permutation.
  1493. Examples
  1494. ========
  1495. >>> from sympy.combinatorics import Permutation
  1496. >>> p = Permutation([0, 1, 2, 3])
  1497. >>> p.rank()
  1498. 0
  1499. >>> p = Permutation([3, 2, 1, 0])
  1500. >>> p.rank()
  1501. 23
  1502. See Also
  1503. ========
  1504. next_lex, unrank_lex, cardinality, length, order, size
  1505. """
  1506. if self._rank is not None:
  1507. return self._rank
  1508. rank = 0
  1509. rho = self.array_form[:]
  1510. n = self.size - 1
  1511. size = n + 1
  1512. psize = int(ifac(n))
  1513. for j in range(size - 1):
  1514. rank += rho[j]*psize
  1515. for i in range(j + 1, size):
  1516. if rho[i] > rho[j]:
  1517. rho[i] -= 1
  1518. psize //= n
  1519. n -= 1
  1520. self._rank = rank
  1521. return rank
  1522. @property
  1523. def cardinality(self):
  1524. """
  1525. Returns the number of all possible permutations.
  1526. Examples
  1527. ========
  1528. >>> from sympy.combinatorics import Permutation
  1529. >>> p = Permutation([0, 1, 2, 3])
  1530. >>> p.cardinality
  1531. 24
  1532. See Also
  1533. ========
  1534. length, order, rank, size
  1535. """
  1536. return int(ifac(self.size))
  1537. def parity(self):
  1538. """
  1539. Computes the parity of a permutation.
  1540. Explanation
  1541. ===========
  1542. The parity of a permutation reflects the parity of the
  1543. number of inversions in the permutation, i.e., the
  1544. number of pairs of x and y such that ``x > y`` but ``p[x] < p[y]``.
  1545. Examples
  1546. ========
  1547. >>> from sympy.combinatorics import Permutation
  1548. >>> p = Permutation([0, 1, 2, 3])
  1549. >>> p.parity()
  1550. 0
  1551. >>> p = Permutation([3, 2, 0, 1])
  1552. >>> p.parity()
  1553. 1
  1554. See Also
  1555. ========
  1556. _af_parity
  1557. """
  1558. if self._cyclic_form is not None:
  1559. return (self.size - self.cycles) % 2
  1560. return _af_parity(self.array_form)
  1561. @property
  1562. def is_even(self):
  1563. """
  1564. Checks if a permutation is even.
  1565. Examples
  1566. ========
  1567. >>> from sympy.combinatorics import Permutation
  1568. >>> p = Permutation([0, 1, 2, 3])
  1569. >>> p.is_even
  1570. True
  1571. >>> p = Permutation([3, 2, 1, 0])
  1572. >>> p.is_even
  1573. True
  1574. See Also
  1575. ========
  1576. is_odd
  1577. """
  1578. return not self.is_odd
  1579. @property
  1580. def is_odd(self):
  1581. """
  1582. Checks if a permutation is odd.
  1583. Examples
  1584. ========
  1585. >>> from sympy.combinatorics import Permutation
  1586. >>> p = Permutation([0, 1, 2, 3])
  1587. >>> p.is_odd
  1588. False
  1589. >>> p = Permutation([3, 2, 0, 1])
  1590. >>> p.is_odd
  1591. True
  1592. See Also
  1593. ========
  1594. is_even
  1595. """
  1596. return bool(self.parity() % 2)
  1597. @property
  1598. def is_Singleton(self):
  1599. """
  1600. Checks to see if the permutation contains only one number and is
  1601. thus the only possible permutation of this set of numbers
  1602. Examples
  1603. ========
  1604. >>> from sympy.combinatorics import Permutation
  1605. >>> Permutation([0]).is_Singleton
  1606. True
  1607. >>> Permutation([0, 1]).is_Singleton
  1608. False
  1609. See Also
  1610. ========
  1611. is_Empty
  1612. """
  1613. return self.size == 1
  1614. @property
  1615. def is_Empty(self):
  1616. """
  1617. Checks to see if the permutation is a set with zero elements
  1618. Examples
  1619. ========
  1620. >>> from sympy.combinatorics import Permutation
  1621. >>> Permutation([]).is_Empty
  1622. True
  1623. >>> Permutation([0]).is_Empty
  1624. False
  1625. See Also
  1626. ========
  1627. is_Singleton
  1628. """
  1629. return self.size == 0
  1630. @property
  1631. def is_identity(self):
  1632. return self.is_Identity
  1633. @property
  1634. def is_Identity(self):
  1635. """
  1636. Returns True if the Permutation is an identity permutation.
  1637. Examples
  1638. ========
  1639. >>> from sympy.combinatorics import Permutation
  1640. >>> p = Permutation([])
  1641. >>> p.is_Identity
  1642. True
  1643. >>> p = Permutation([[0], [1], [2]])
  1644. >>> p.is_Identity
  1645. True
  1646. >>> p = Permutation([0, 1, 2])
  1647. >>> p.is_Identity
  1648. True
  1649. >>> p = Permutation([0, 2, 1])
  1650. >>> p.is_Identity
  1651. False
  1652. See Also
  1653. ========
  1654. order
  1655. """
  1656. af = self.array_form
  1657. return not af or all(i == af[i] for i in range(self.size))
  1658. def ascents(self):
  1659. """
  1660. Returns the positions of ascents in a permutation, ie, the location
  1661. where p[i] < p[i+1]
  1662. Examples
  1663. ========
  1664. >>> from sympy.combinatorics import Permutation
  1665. >>> p = Permutation([4, 0, 1, 3, 2])
  1666. >>> p.ascents()
  1667. [1, 2]
  1668. See Also
  1669. ========
  1670. descents, inversions, min, max
  1671. """
  1672. a = self.array_form
  1673. pos = [i for i in range(len(a) - 1) if a[i] < a[i + 1]]
  1674. return pos
  1675. def descents(self):
  1676. """
  1677. Returns the positions of descents in a permutation, ie, the location
  1678. where p[i] > p[i+1]
  1679. Examples
  1680. ========
  1681. >>> from sympy.combinatorics import Permutation
  1682. >>> p = Permutation([4, 0, 1, 3, 2])
  1683. >>> p.descents()
  1684. [0, 3]
  1685. See Also
  1686. ========
  1687. ascents, inversions, min, max
  1688. """
  1689. a = self.array_form
  1690. pos = [i for i in range(len(a) - 1) if a[i] > a[i + 1]]
  1691. return pos
  1692. def max(self):
  1693. """
  1694. The maximum element moved by the permutation.
  1695. Examples
  1696. ========
  1697. >>> from sympy.combinatorics import Permutation
  1698. >>> p = Permutation([1, 0, 2, 3, 4])
  1699. >>> p.max()
  1700. 1
  1701. See Also
  1702. ========
  1703. min, descents, ascents, inversions
  1704. """
  1705. max = 0
  1706. a = self.array_form
  1707. for i in range(len(a)):
  1708. if a[i] != i and a[i] > max:
  1709. max = a[i]
  1710. return max
  1711. def min(self):
  1712. """
  1713. The minimum element moved by the permutation.
  1714. Examples
  1715. ========
  1716. >>> from sympy.combinatorics import Permutation
  1717. >>> p = Permutation([0, 1, 4, 3, 2])
  1718. >>> p.min()
  1719. 2
  1720. See Also
  1721. ========
  1722. max, descents, ascents, inversions
  1723. """
  1724. a = self.array_form
  1725. min = len(a)
  1726. for i in range(len(a)):
  1727. if a[i] != i and a[i] < min:
  1728. min = a[i]
  1729. return min
  1730. def inversions(self):
  1731. """
  1732. Computes the number of inversions of a permutation.
  1733. Explanation
  1734. ===========
  1735. An inversion is where i > j but p[i] < p[j].
  1736. For small length of p, it iterates over all i and j
  1737. values and calculates the number of inversions.
  1738. For large length of p, it uses a variation of merge
  1739. sort to calculate the number of inversions.
  1740. Examples
  1741. ========
  1742. >>> from sympy.combinatorics import Permutation
  1743. >>> p = Permutation([0, 1, 2, 3, 4, 5])
  1744. >>> p.inversions()
  1745. 0
  1746. >>> Permutation([3, 2, 1, 0]).inversions()
  1747. 6
  1748. See Also
  1749. ========
  1750. descents, ascents, min, max
  1751. References
  1752. ==========
  1753. .. [1] https://www.cp.eng.chula.ac.th/~prabhas//teaching/algo/algo2008/count-inv.htm
  1754. """
  1755. inversions = 0
  1756. a = self.array_form
  1757. n = len(a)
  1758. if n < 130:
  1759. for i in range(n - 1):
  1760. b = a[i]
  1761. for c in a[i + 1:]:
  1762. if b > c:
  1763. inversions += 1
  1764. else:
  1765. k = 1
  1766. right = 0
  1767. arr = a[:]
  1768. temp = a[:]
  1769. while k < n:
  1770. i = 0
  1771. while i + k < n:
  1772. right = i + k * 2 - 1
  1773. if right >= n:
  1774. right = n - 1
  1775. inversions += _merge(arr, temp, i, i + k, right)
  1776. i = i + k * 2
  1777. k = k * 2
  1778. return inversions
  1779. def commutator(self, x):
  1780. """Return the commutator of ``self`` and ``x``: ``~x*~self*x*self``
  1781. If f and g are part of a group, G, then the commutator of f and g
  1782. is the group identity iff f and g commute, i.e. fg == gf.
  1783. Examples
  1784. ========
  1785. >>> from sympy.combinatorics import Permutation
  1786. >>> from sympy import init_printing
  1787. >>> init_printing(perm_cyclic=False, pretty_print=False)
  1788. >>> p = Permutation([0, 2, 3, 1])
  1789. >>> x = Permutation([2, 0, 3, 1])
  1790. >>> c = p.commutator(x); c
  1791. Permutation([2, 1, 3, 0])
  1792. >>> c == ~x*~p*x*p
  1793. True
  1794. >>> I = Permutation(3)
  1795. >>> p = [I + i for i in range(6)]
  1796. >>> for i in range(len(p)):
  1797. ... for j in range(len(p)):
  1798. ... c = p[i].commutator(p[j])
  1799. ... if p[i]*p[j] == p[j]*p[i]:
  1800. ... assert c == I
  1801. ... else:
  1802. ... assert c != I
  1803. ...
  1804. References
  1805. ==========
  1806. .. [1] https://en.wikipedia.org/wiki/Commutator
  1807. """
  1808. a = self.array_form
  1809. b = x.array_form
  1810. n = len(a)
  1811. if len(b) != n:
  1812. raise ValueError("The permutations must be of equal size.")
  1813. inva = [None]*n
  1814. for i in range(n):
  1815. inva[a[i]] = i
  1816. invb = [None]*n
  1817. for i in range(n):
  1818. invb[b[i]] = i
  1819. return self._af_new([a[b[inva[i]]] for i in invb])
  1820. def signature(self):
  1821. """
  1822. Gives the signature of the permutation needed to place the
  1823. elements of the permutation in canonical order.
  1824. The signature is calculated as (-1)^<number of inversions>
  1825. Examples
  1826. ========
  1827. >>> from sympy.combinatorics import Permutation
  1828. >>> p = Permutation([0, 1, 2])
  1829. >>> p.inversions()
  1830. 0
  1831. >>> p.signature()
  1832. 1
  1833. >>> q = Permutation([0,2,1])
  1834. >>> q.inversions()
  1835. 1
  1836. >>> q.signature()
  1837. -1
  1838. See Also
  1839. ========
  1840. inversions
  1841. """
  1842. if self.is_even:
  1843. return 1
  1844. return -1
  1845. def order(self):
  1846. """
  1847. Computes the order of a permutation.
  1848. When the permutation is raised to the power of its
  1849. order it equals the identity permutation.
  1850. Examples
  1851. ========
  1852. >>> from sympy.combinatorics import Permutation
  1853. >>> from sympy import init_printing
  1854. >>> init_printing(perm_cyclic=False, pretty_print=False)
  1855. >>> p = Permutation([3, 1, 5, 2, 4, 0])
  1856. >>> p.order()
  1857. 4
  1858. >>> (p**(p.order()))
  1859. Permutation([], size=6)
  1860. See Also
  1861. ========
  1862. identity, cardinality, length, rank, size
  1863. """
  1864. return reduce(lcm, [len(cycle) for cycle in self.cyclic_form], 1)
  1865. def length(self):
  1866. """
  1867. Returns the number of integers moved by a permutation.
  1868. Examples
  1869. ========
  1870. >>> from sympy.combinatorics import Permutation
  1871. >>> Permutation([0, 3, 2, 1]).length()
  1872. 2
  1873. >>> Permutation([[0, 1], [2, 3]]).length()
  1874. 4
  1875. See Also
  1876. ========
  1877. min, max, support, cardinality, order, rank, size
  1878. """
  1879. return len(self.support())
  1880. @property
  1881. def cycle_structure(self):
  1882. """Return the cycle structure of the permutation as a dictionary
  1883. indicating the multiplicity of each cycle length.
  1884. Examples
  1885. ========
  1886. >>> from sympy.combinatorics import Permutation
  1887. >>> Permutation(3).cycle_structure
  1888. {1: 4}
  1889. >>> Permutation(0, 4, 3)(1, 2)(5, 6).cycle_structure
  1890. {2: 2, 3: 1}
  1891. """
  1892. if self._cycle_structure:
  1893. rv = self._cycle_structure
  1894. else:
  1895. rv = defaultdict(int)
  1896. singletons = self.size
  1897. for c in self.cyclic_form:
  1898. rv[len(c)] += 1
  1899. singletons -= len(c)
  1900. if singletons:
  1901. rv[1] = singletons
  1902. self._cycle_structure = rv
  1903. return dict(rv) # make a copy
  1904. @property
  1905. def cycles(self):
  1906. """
  1907. Returns the number of cycles contained in the permutation
  1908. (including singletons).
  1909. Examples
  1910. ========
  1911. >>> from sympy.combinatorics import Permutation
  1912. >>> Permutation([0, 1, 2]).cycles
  1913. 3
  1914. >>> Permutation([0, 1, 2]).full_cyclic_form
  1915. [[0], [1], [2]]
  1916. >>> Permutation(0, 1)(2, 3).cycles
  1917. 2
  1918. See Also
  1919. ========
  1920. sympy.functions.combinatorial.numbers.stirling
  1921. """
  1922. return len(self.full_cyclic_form)
  1923. def index(self):
  1924. """
  1925. Returns the index of a permutation.
  1926. The index of a permutation is the sum of all subscripts j such
  1927. that p[j] is greater than p[j+1].
  1928. Examples
  1929. ========
  1930. >>> from sympy.combinatorics import Permutation
  1931. >>> p = Permutation([3, 0, 2, 1, 4])
  1932. >>> p.index()
  1933. 2
  1934. """
  1935. a = self.array_form
  1936. return sum([j for j in range(len(a) - 1) if a[j] > a[j + 1]])
  1937. def runs(self):
  1938. """
  1939. Returns the runs of a permutation.
  1940. An ascending sequence in a permutation is called a run [5].
  1941. Examples
  1942. ========
  1943. >>> from sympy.combinatorics import Permutation
  1944. >>> p = Permutation([2, 5, 7, 3, 6, 0, 1, 4, 8])
  1945. >>> p.runs()
  1946. [[2, 5, 7], [3, 6], [0, 1, 4, 8]]
  1947. >>> q = Permutation([1,3,2,0])
  1948. >>> q.runs()
  1949. [[1, 3], [2], [0]]
  1950. """
  1951. return runs(self.array_form)
  1952. def inversion_vector(self):
  1953. """Return the inversion vector of the permutation.
  1954. The inversion vector consists of elements whose value
  1955. indicates the number of elements in the permutation
  1956. that are lesser than it and lie on its right hand side.
  1957. The inversion vector is the same as the Lehmer encoding of a
  1958. permutation.
  1959. Examples
  1960. ========
  1961. >>> from sympy.combinatorics import Permutation
  1962. >>> p = Permutation([4, 8, 0, 7, 1, 5, 3, 6, 2])
  1963. >>> p.inversion_vector()
  1964. [4, 7, 0, 5, 0, 2, 1, 1]
  1965. >>> p = Permutation([3, 2, 1, 0])
  1966. >>> p.inversion_vector()
  1967. [3, 2, 1]
  1968. The inversion vector increases lexicographically with the rank
  1969. of the permutation, the -ith element cycling through 0..i.
  1970. >>> p = Permutation(2)
  1971. >>> while p:
  1972. ... print('%s %s %s' % (p, p.inversion_vector(), p.rank()))
  1973. ... p = p.next_lex()
  1974. (2) [0, 0] 0
  1975. (1 2) [0, 1] 1
  1976. (2)(0 1) [1, 0] 2
  1977. (0 1 2) [1, 1] 3
  1978. (0 2 1) [2, 0] 4
  1979. (0 2) [2, 1] 5
  1980. See Also
  1981. ========
  1982. from_inversion_vector
  1983. """
  1984. self_array_form = self.array_form
  1985. n = len(self_array_form)
  1986. inversion_vector = [0] * (n - 1)
  1987. for i in range(n - 1):
  1988. val = 0
  1989. for j in range(i + 1, n):
  1990. if self_array_form[j] < self_array_form[i]:
  1991. val += 1
  1992. inversion_vector[i] = val
  1993. return inversion_vector
  1994. def rank_trotterjohnson(self):
  1995. """
  1996. Returns the Trotter Johnson rank, which we get from the minimal
  1997. change algorithm. See [4] section 2.4.
  1998. Examples
  1999. ========
  2000. >>> from sympy.combinatorics import Permutation
  2001. >>> p = Permutation([0, 1, 2, 3])
  2002. >>> p.rank_trotterjohnson()
  2003. 0
  2004. >>> p = Permutation([0, 2, 1, 3])
  2005. >>> p.rank_trotterjohnson()
  2006. 7
  2007. See Also
  2008. ========
  2009. unrank_trotterjohnson, next_trotterjohnson
  2010. """
  2011. if self.array_form == [] or self.is_Identity:
  2012. return 0
  2013. if self.array_form == [1, 0]:
  2014. return 1
  2015. perm = self.array_form
  2016. n = self.size
  2017. rank = 0
  2018. for j in range(1, n):
  2019. k = 1
  2020. i = 0
  2021. while perm[i] != j:
  2022. if perm[i] < j:
  2023. k += 1
  2024. i += 1
  2025. j1 = j + 1
  2026. if rank % 2 == 0:
  2027. rank = j1*rank + j1 - k
  2028. else:
  2029. rank = j1*rank + k - 1
  2030. return rank
  2031. @classmethod
  2032. def unrank_trotterjohnson(cls, size, rank):
  2033. """
  2034. Trotter Johnson permutation unranking. See [4] section 2.4.
  2035. Examples
  2036. ========
  2037. >>> from sympy.combinatorics import Permutation
  2038. >>> from sympy import init_printing
  2039. >>> init_printing(perm_cyclic=False, pretty_print=False)
  2040. >>> Permutation.unrank_trotterjohnson(5, 10)
  2041. Permutation([0, 3, 1, 2, 4])
  2042. See Also
  2043. ========
  2044. rank_trotterjohnson, next_trotterjohnson
  2045. """
  2046. perm = [0]*size
  2047. r2 = 0
  2048. n = ifac(size)
  2049. pj = 1
  2050. for j in range(2, size + 1):
  2051. pj *= j
  2052. r1 = (rank * pj) // n
  2053. k = r1 - j*r2
  2054. if r2 % 2 == 0:
  2055. for i in range(j - 1, j - k - 1, -1):
  2056. perm[i] = perm[i - 1]
  2057. perm[j - k - 1] = j - 1
  2058. else:
  2059. for i in range(j - 1, k, -1):
  2060. perm[i] = perm[i - 1]
  2061. perm[k] = j - 1
  2062. r2 = r1
  2063. return cls._af_new(perm)
  2064. def next_trotterjohnson(self):
  2065. """
  2066. Returns the next permutation in Trotter-Johnson order.
  2067. If self is the last permutation it returns None.
  2068. See [4] section 2.4. If it is desired to generate all such
  2069. permutations, they can be generated in order more quickly
  2070. with the ``generate_bell`` function.
  2071. Examples
  2072. ========
  2073. >>> from sympy.combinatorics import Permutation
  2074. >>> from sympy import init_printing
  2075. >>> init_printing(perm_cyclic=False, pretty_print=False)
  2076. >>> p = Permutation([3, 0, 2, 1])
  2077. >>> p.rank_trotterjohnson()
  2078. 4
  2079. >>> p = p.next_trotterjohnson(); p
  2080. Permutation([0, 3, 2, 1])
  2081. >>> p.rank_trotterjohnson()
  2082. 5
  2083. See Also
  2084. ========
  2085. rank_trotterjohnson, unrank_trotterjohnson, sympy.utilities.iterables.generate_bell
  2086. """
  2087. pi = self.array_form[:]
  2088. n = len(pi)
  2089. st = 0
  2090. rho = pi[:]
  2091. done = False
  2092. m = n-1
  2093. while m > 0 and not done:
  2094. d = rho.index(m)
  2095. for i in range(d, m):
  2096. rho[i] = rho[i + 1]
  2097. par = _af_parity(rho[:m])
  2098. if par == 1:
  2099. if d == m:
  2100. m -= 1
  2101. else:
  2102. pi[st + d], pi[st + d + 1] = pi[st + d + 1], pi[st + d]
  2103. done = True
  2104. else:
  2105. if d == 0:
  2106. m -= 1
  2107. st += 1
  2108. else:
  2109. pi[st + d], pi[st + d - 1] = pi[st + d - 1], pi[st + d]
  2110. done = True
  2111. if m == 0:
  2112. return None
  2113. return self._af_new(pi)
  2114. def get_precedence_matrix(self):
  2115. """
  2116. Gets the precedence matrix. This is used for computing the
  2117. distance between two permutations.
  2118. Examples
  2119. ========
  2120. >>> from sympy.combinatorics import Permutation
  2121. >>> from sympy import init_printing
  2122. >>> init_printing(perm_cyclic=False, pretty_print=False)
  2123. >>> p = Permutation.josephus(3, 6, 1)
  2124. >>> p
  2125. Permutation([2, 5, 3, 1, 4, 0])
  2126. >>> p.get_precedence_matrix()
  2127. Matrix([
  2128. [0, 0, 0, 0, 0, 0],
  2129. [1, 0, 0, 0, 1, 0],
  2130. [1, 1, 0, 1, 1, 1],
  2131. [1, 1, 0, 0, 1, 0],
  2132. [1, 0, 0, 0, 0, 0],
  2133. [1, 1, 0, 1, 1, 0]])
  2134. See Also
  2135. ========
  2136. get_precedence_distance, get_adjacency_matrix, get_adjacency_distance
  2137. """
  2138. m = zeros(self.size)
  2139. perm = self.array_form
  2140. for i in range(m.rows):
  2141. for j in range(i + 1, m.cols):
  2142. m[perm[i], perm[j]] = 1
  2143. return m
  2144. def get_precedence_distance(self, other):
  2145. """
  2146. Computes the precedence distance between two permutations.
  2147. Explanation
  2148. ===========
  2149. Suppose p and p' represent n jobs. The precedence metric
  2150. counts the number of times a job j is preceded by job i
  2151. in both p and p'. This metric is commutative.
  2152. Examples
  2153. ========
  2154. >>> from sympy.combinatorics import Permutation
  2155. >>> p = Permutation([2, 0, 4, 3, 1])
  2156. >>> q = Permutation([3, 1, 2, 4, 0])
  2157. >>> p.get_precedence_distance(q)
  2158. 7
  2159. >>> q.get_precedence_distance(p)
  2160. 7
  2161. See Also
  2162. ========
  2163. get_precedence_matrix, get_adjacency_matrix, get_adjacency_distance
  2164. """
  2165. if self.size != other.size:
  2166. raise ValueError("The permutations must be of equal size.")
  2167. self_prec_mat = self.get_precedence_matrix()
  2168. other_prec_mat = other.get_precedence_matrix()
  2169. n_prec = 0
  2170. for i in range(self.size):
  2171. for j in range(self.size):
  2172. if i == j:
  2173. continue
  2174. if self_prec_mat[i, j] * other_prec_mat[i, j] == 1:
  2175. n_prec += 1
  2176. d = self.size * (self.size - 1)//2 - n_prec
  2177. return d
  2178. def get_adjacency_matrix(self):
  2179. """
  2180. Computes the adjacency matrix of a permutation.
  2181. Explanation
  2182. ===========
  2183. If job i is adjacent to job j in a permutation p
  2184. then we set m[i, j] = 1 where m is the adjacency
  2185. matrix of p.
  2186. Examples
  2187. ========
  2188. >>> from sympy.combinatorics import Permutation
  2189. >>> p = Permutation.josephus(3, 6, 1)
  2190. >>> p.get_adjacency_matrix()
  2191. Matrix([
  2192. [0, 0, 0, 0, 0, 0],
  2193. [0, 0, 0, 0, 1, 0],
  2194. [0, 0, 0, 0, 0, 1],
  2195. [0, 1, 0, 0, 0, 0],
  2196. [1, 0, 0, 0, 0, 0],
  2197. [0, 0, 0, 1, 0, 0]])
  2198. >>> q = Permutation([0, 1, 2, 3])
  2199. >>> q.get_adjacency_matrix()
  2200. Matrix([
  2201. [0, 1, 0, 0],
  2202. [0, 0, 1, 0],
  2203. [0, 0, 0, 1],
  2204. [0, 0, 0, 0]])
  2205. See Also
  2206. ========
  2207. get_precedence_matrix, get_precedence_distance, get_adjacency_distance
  2208. """
  2209. m = zeros(self.size)
  2210. perm = self.array_form
  2211. for i in range(self.size - 1):
  2212. m[perm[i], perm[i + 1]] = 1
  2213. return m
  2214. def get_adjacency_distance(self, other):
  2215. """
  2216. Computes the adjacency distance between two permutations.
  2217. Explanation
  2218. ===========
  2219. This metric counts the number of times a pair i,j of jobs is
  2220. adjacent in both p and p'. If n_adj is this quantity then
  2221. the adjacency distance is n - n_adj - 1 [1]
  2222. [1] Reeves, Colin R. Landscapes, Operators and Heuristic search, Annals
  2223. of Operational Research, 86, pp 473-490. (1999)
  2224. Examples
  2225. ========
  2226. >>> from sympy.combinatorics import Permutation
  2227. >>> p = Permutation([0, 3, 1, 2, 4])
  2228. >>> q = Permutation.josephus(4, 5, 2)
  2229. >>> p.get_adjacency_distance(q)
  2230. 3
  2231. >>> r = Permutation([0, 2, 1, 4, 3])
  2232. >>> p.get_adjacency_distance(r)
  2233. 4
  2234. See Also
  2235. ========
  2236. get_precedence_matrix, get_precedence_distance, get_adjacency_matrix
  2237. """
  2238. if self.size != other.size:
  2239. raise ValueError("The permutations must be of the same size.")
  2240. self_adj_mat = self.get_adjacency_matrix()
  2241. other_adj_mat = other.get_adjacency_matrix()
  2242. n_adj = 0
  2243. for i in range(self.size):
  2244. for j in range(self.size):
  2245. if i == j:
  2246. continue
  2247. if self_adj_mat[i, j] * other_adj_mat[i, j] == 1:
  2248. n_adj += 1
  2249. d = self.size - n_adj - 1
  2250. return d
  2251. def get_positional_distance(self, other):
  2252. """
  2253. Computes the positional distance between two permutations.
  2254. Examples
  2255. ========
  2256. >>> from sympy.combinatorics import Permutation
  2257. >>> p = Permutation([0, 3, 1, 2, 4])
  2258. >>> q = Permutation.josephus(4, 5, 2)
  2259. >>> r = Permutation([3, 1, 4, 0, 2])
  2260. >>> p.get_positional_distance(q)
  2261. 12
  2262. >>> p.get_positional_distance(r)
  2263. 12
  2264. See Also
  2265. ========
  2266. get_precedence_distance, get_adjacency_distance
  2267. """
  2268. a = self.array_form
  2269. b = other.array_form
  2270. if len(a) != len(b):
  2271. raise ValueError("The permutations must be of the same size.")
  2272. return sum([abs(a[i] - b[i]) for i in range(len(a))])
  2273. @classmethod
  2274. def josephus(cls, m, n, s=1):
  2275. """Return as a permutation the shuffling of range(n) using the Josephus
  2276. scheme in which every m-th item is selected until all have been chosen.
  2277. The returned permutation has elements listed by the order in which they
  2278. were selected.
  2279. The parameter ``s`` stops the selection process when there are ``s``
  2280. items remaining and these are selected by continuing the selection,
  2281. counting by 1 rather than by ``m``.
  2282. Consider selecting every 3rd item from 6 until only 2 remain::
  2283. choices chosen
  2284. ======== ======
  2285. 012345
  2286. 01 345 2
  2287. 01 34 25
  2288. 01 4 253
  2289. 0 4 2531
  2290. 0 25314
  2291. 253140
  2292. Examples
  2293. ========
  2294. >>> from sympy.combinatorics import Permutation
  2295. >>> Permutation.josephus(3, 6, 2).array_form
  2296. [2, 5, 3, 1, 4, 0]
  2297. References
  2298. ==========
  2299. .. [1] https://en.wikipedia.org/wiki/Flavius_Josephus
  2300. .. [2] https://en.wikipedia.org/wiki/Josephus_problem
  2301. .. [3] https://web.archive.org/web/20171008094331/http://www.wou.edu/~burtonl/josephus.html
  2302. """
  2303. from collections import deque
  2304. m -= 1
  2305. Q = deque(list(range(n)))
  2306. perm = []
  2307. while len(Q) > max(s, 1):
  2308. for dp in range(m):
  2309. Q.append(Q.popleft())
  2310. perm.append(Q.popleft())
  2311. perm.extend(list(Q))
  2312. return cls(perm)
  2313. @classmethod
  2314. def from_inversion_vector(cls, inversion):
  2315. """
  2316. Calculates the permutation from the inversion vector.
  2317. Examples
  2318. ========
  2319. >>> from sympy.combinatorics import Permutation
  2320. >>> from sympy import init_printing
  2321. >>> init_printing(perm_cyclic=False, pretty_print=False)
  2322. >>> Permutation.from_inversion_vector([3, 2, 1, 0, 0])
  2323. Permutation([3, 2, 1, 0, 4, 5])
  2324. """
  2325. size = len(inversion)
  2326. N = list(range(size + 1))
  2327. perm = []
  2328. try:
  2329. for k in range(size):
  2330. val = N[inversion[k]]
  2331. perm.append(val)
  2332. N.remove(val)
  2333. except IndexError:
  2334. raise ValueError("The inversion vector is not valid.")
  2335. perm.extend(N)
  2336. return cls._af_new(perm)
  2337. @classmethod
  2338. def random(cls, n):
  2339. """
  2340. Generates a random permutation of length ``n``.
  2341. Uses the underlying Python pseudo-random number generator.
  2342. Examples
  2343. ========
  2344. >>> from sympy.combinatorics import Permutation
  2345. >>> Permutation.random(2) in (Permutation([1, 0]), Permutation([0, 1]))
  2346. True
  2347. """
  2348. perm_array = list(range(n))
  2349. random.shuffle(perm_array)
  2350. return cls._af_new(perm_array)
  2351. @classmethod
  2352. def unrank_lex(cls, size, rank):
  2353. """
  2354. Lexicographic permutation unranking.
  2355. Examples
  2356. ========
  2357. >>> from sympy.combinatorics import Permutation
  2358. >>> from sympy import init_printing
  2359. >>> init_printing(perm_cyclic=False, pretty_print=False)
  2360. >>> a = Permutation.unrank_lex(5, 10)
  2361. >>> a.rank()
  2362. 10
  2363. >>> a
  2364. Permutation([0, 2, 4, 1, 3])
  2365. See Also
  2366. ========
  2367. rank, next_lex
  2368. """
  2369. perm_array = [0] * size
  2370. psize = 1
  2371. for i in range(size):
  2372. new_psize = psize*(i + 1)
  2373. d = (rank % new_psize) // psize
  2374. rank -= d*psize
  2375. perm_array[size - i - 1] = d
  2376. for j in range(size - i, size):
  2377. if perm_array[j] > d - 1:
  2378. perm_array[j] += 1
  2379. psize = new_psize
  2380. return cls._af_new(perm_array)
  2381. def resize(self, n):
  2382. """Resize the permutation to the new size ``n``.
  2383. Parameters
  2384. ==========
  2385. n : int
  2386. The new size of the permutation.
  2387. Raises
  2388. ======
  2389. ValueError
  2390. If the permutation cannot be resized to the given size.
  2391. This may only happen when resized to a smaller size than
  2392. the original.
  2393. Examples
  2394. ========
  2395. >>> from sympy.combinatorics import Permutation
  2396. Increasing the size of a permutation:
  2397. >>> p = Permutation(0, 1, 2)
  2398. >>> p = p.resize(5)
  2399. >>> p
  2400. (4)(0 1 2)
  2401. Decreasing the size of the permutation:
  2402. >>> p = p.resize(4)
  2403. >>> p
  2404. (3)(0 1 2)
  2405. If resizing to the specific size breaks the cycles:
  2406. >>> p.resize(2)
  2407. Traceback (most recent call last):
  2408. ...
  2409. ValueError: The permutation cannot be resized to 2 because the
  2410. cycle (0, 1, 2) may break.
  2411. """
  2412. aform = self.array_form
  2413. l = len(aform)
  2414. if n > l:
  2415. aform += list(range(l, n))
  2416. return Permutation._af_new(aform)
  2417. elif n < l:
  2418. cyclic_form = self.full_cyclic_form
  2419. new_cyclic_form = []
  2420. for cycle in cyclic_form:
  2421. cycle_min = min(cycle)
  2422. cycle_max = max(cycle)
  2423. if cycle_min <= n-1:
  2424. if cycle_max > n-1:
  2425. raise ValueError(
  2426. "The permutation cannot be resized to {} "
  2427. "because the cycle {} may break."
  2428. .format(n, tuple(cycle)))
  2429. new_cyclic_form.append(cycle)
  2430. return Permutation(new_cyclic_form)
  2431. return self
  2432. # XXX Deprecated flag
  2433. print_cyclic = None
  2434. def _merge(arr, temp, left, mid, right):
  2435. """
  2436. Merges two sorted arrays and calculates the inversion count.
  2437. Helper function for calculating inversions. This method is
  2438. for internal use only.
  2439. """
  2440. i = k = left
  2441. j = mid
  2442. inv_count = 0
  2443. while i < mid and j <= right:
  2444. if arr[i] < arr[j]:
  2445. temp[k] = arr[i]
  2446. k += 1
  2447. i += 1
  2448. else:
  2449. temp[k] = arr[j]
  2450. k += 1
  2451. j += 1
  2452. inv_count += (mid -i)
  2453. while i < mid:
  2454. temp[k] = arr[i]
  2455. k += 1
  2456. i += 1
  2457. if j <= right:
  2458. k += right - j + 1
  2459. j += right - j + 1
  2460. arr[left:k + 1] = temp[left:k + 1]
  2461. else:
  2462. arr[left:right + 1] = temp[left:right + 1]
  2463. return inv_count
  2464. Perm = Permutation
  2465. _af_new = Perm._af_new
  2466. class AppliedPermutation(Expr):
  2467. """A permutation applied to a symbolic variable.
  2468. Parameters
  2469. ==========
  2470. perm : Permutation
  2471. x : Expr
  2472. Examples
  2473. ========
  2474. >>> from sympy import Symbol
  2475. >>> from sympy.combinatorics import Permutation
  2476. Creating a symbolic permutation function application:
  2477. >>> x = Symbol('x')
  2478. >>> p = Permutation(0, 1, 2)
  2479. >>> p.apply(x)
  2480. AppliedPermutation((0 1 2), x)
  2481. >>> _.subs(x, 1)
  2482. 2
  2483. """
  2484. def __new__(cls, perm, x, evaluate=None):
  2485. if evaluate is None:
  2486. evaluate = global_parameters.evaluate
  2487. perm = _sympify(perm)
  2488. x = _sympify(x)
  2489. if not isinstance(perm, Permutation):
  2490. raise ValueError("{} must be a Permutation instance."
  2491. .format(perm))
  2492. if evaluate:
  2493. if x.is_Integer:
  2494. return perm.apply(x)
  2495. obj = super().__new__(cls, perm, x)
  2496. return obj
  2497. @dispatch(Permutation, Permutation)
  2498. def _eval_is_eq(lhs, rhs):
  2499. if lhs._size != rhs._size:
  2500. return None
  2501. return lhs._array_form == rhs._array_form