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.utilities.iterables import (flatten, has_variety, minlex,
  13. has_dups, runs, is_sequence)
  14. from sympy.utilities.misc import as_int
  15. from mpmath.libmp.libintmath import ifac
  16. from sympy.multipledispatch import dispatch
  17. def _af_rmul(a, b):
  18. """
  19. Return the product b*a; input and output are array forms. The ith value
  20. is a[b[i]].
  21. Examples
  22. ========
  23. >>> from sympy.combinatorics.permutations import _af_rmul, Permutation
  24. >>> a, b = [1, 0, 2], [0, 2, 1]
  25. >>> _af_rmul(a, b)
  26. [1, 2, 0]
  27. >>> [a[b[i]] for i in range(3)]
  28. [1, 2, 0]
  29. This handles the operands in reverse order compared to the ``*`` operator:
  30. >>> a = Permutation(a)
  31. >>> b = Permutation(b)
  32. >>> list(a*b)
  33. [2, 0, 1]
  34. >>> [b(a(i)) for i in range(3)]
  35. [2, 0, 1]
  36. See Also
  37. ========
  38. rmul, _af_rmuln
  39. """
  40. return [a[i] for i in b]
  41. def _af_rmuln(*abc):
  42. """
  43. Given [a, b, c, ...] return the product of ...*c*b*a using array forms.
  44. The ith value is a[b[c[i]]].
  45. Examples
  46. ========
  47. >>> from sympy.combinatorics.permutations import _af_rmul, Permutation
  48. >>> a, b = [1, 0, 2], [0, 2, 1]
  49. >>> _af_rmul(a, b)
  50. [1, 2, 0]
  51. >>> [a[b[i]] for i in range(3)]
  52. [1, 2, 0]
  53. This handles the operands in reverse order compared to the ``*`` operator:
  54. >>> a = Permutation(a); b = Permutation(b)
  55. >>> list(a*b)
  56. [2, 0, 1]
  57. >>> [b(a(i)) for i in range(3)]
  58. [2, 0, 1]
  59. See Also
  60. ========
  61. rmul, _af_rmul
  62. """
  63. a = abc
  64. m = len(a)
  65. if m == 3:
  66. p0, p1, p2 = a
  67. return [p0[p1[i]] for i in p2]
  68. if m == 4:
  69. p0, p1, p2, p3 = a
  70. return [p0[p1[p2[i]]] for i in p3]
  71. if m == 5:
  72. p0, p1, p2, p3, p4 = a
  73. return [p0[p1[p2[p3[i]]]] for i in p4]
  74. if m == 6:
  75. p0, p1, p2, p3, p4, p5 = a
  76. return [p0[p1[p2[p3[p4[i]]]]] for i in p5]
  77. if m == 7:
  78. p0, p1, p2, p3, p4, p5, p6 = a
  79. return [p0[p1[p2[p3[p4[p5[i]]]]]] for i in p6]
  80. if m == 8:
  81. p0, p1, p2, p3, p4, p5, p6, p7 = a
  82. return [p0[p1[p2[p3[p4[p5[p6[i]]]]]]] for i in p7]
  83. if m == 1:
  84. return a[0][:]
  85. if m == 2:
  86. a, b = a
  87. return [a[i] for i in b]
  88. if m == 0:
  89. raise ValueError("String must not be empty")
  90. p0 = _af_rmuln(*a[:m//2])
  91. p1 = _af_rmuln(*a[m//2:])
  92. return [p0[i] for i in p1]
  93. def _af_parity(pi):
  94. """
  95. Computes the parity of a permutation in array form.
  96. Explanation
  97. ===========
  98. The parity of a permutation reflects the parity of the
  99. number of inversions in the permutation, i.e., the
  100. number of pairs of x and y such that x > y but p[x] < p[y].
  101. Examples
  102. ========
  103. >>> from sympy.combinatorics.permutations import _af_parity
  104. >>> _af_parity([0, 1, 2, 3])
  105. 0
  106. >>> _af_parity([3, 2, 0, 1])
  107. 1
  108. See Also
  109. ========
  110. Permutation
  111. """
  112. n = len(pi)
  113. a = [0] * n
  114. c = 0
  115. for j in range(n):
  116. if a[j] == 0:
  117. c += 1
  118. a[j] = 1
  119. i = j
  120. while pi[i] != j:
  121. i = pi[i]
  122. a[i] = 1
  123. return (n - c) % 2
  124. def _af_invert(a):
  125. """
  126. Finds the inverse, ~A, of a permutation, A, given in array form.
  127. Examples
  128. ========
  129. >>> from sympy.combinatorics.permutations import _af_invert, _af_rmul
  130. >>> A = [1, 2, 0, 3]
  131. >>> _af_invert(A)
  132. [2, 0, 1, 3]
  133. >>> _af_rmul(_, A)
  134. [0, 1, 2, 3]
  135. See Also
  136. ========
  137. Permutation, __invert__
  138. """
  139. inv_form = [0] * len(a)
  140. for i, ai in enumerate(a):
  141. inv_form[ai] = i
  142. return inv_form
  143. def _af_pow(a, n):
  144. """
  145. Routine for finding powers of a permutation.
  146. Examples
  147. ========
  148. >>> from sympy.combinatorics import Permutation
  149. >>> from sympy.combinatorics.permutations import _af_pow
  150. >>> p = Permutation([2, 0, 3, 1])
  151. >>> p.order()
  152. 4
  153. >>> _af_pow(p._array_form, 4)
  154. [0, 1, 2, 3]
  155. """
  156. if n == 0:
  157. return list(range(len(a)))
  158. if n < 0:
  159. return _af_pow(_af_invert(a), -n)
  160. if n == 1:
  161. return a[:]
  162. elif n == 2:
  163. b = [a[i] for i in a]
  164. elif n == 3:
  165. b = [a[a[i]] for i in a]
  166. elif n == 4:
  167. b = [a[a[a[i]]] for i in a]
  168. else:
  169. # use binary multiplication
  170. b = list(range(len(a)))
  171. while 1:
  172. if n & 1:
  173. b = [b[i] for i in a]
  174. n -= 1
  175. if not n:
  176. break
  177. if n % 4 == 0:
  178. a = [a[a[a[i]]] for i in a]
  179. n = n // 4
  180. elif n % 2 == 0:
  181. a = [a[i] for i in a]
  182. n = n // 2
  183. return b
  184. def _af_commutes_with(a, b):
  185. """
  186. Checks if the two permutations with array forms
  187. given by ``a`` and ``b`` commute.
  188. Examples
  189. ========
  190. >>> from sympy.combinatorics.permutations import _af_commutes_with
  191. >>> _af_commutes_with([1, 2, 0], [0, 2, 1])
  192. False
  193. See Also
  194. ========
  195. Permutation, commutes_with
  196. """
  197. return not any(a[b[i]] != b[a[i]] for i in range(len(a) - 1))
  198. class Cycle(dict):
  199. """
  200. Wrapper around dict which provides the functionality of a disjoint cycle.
  201. Explanation
  202. ===========
  203. A cycle shows the rule to use to move subsets of elements to obtain
  204. a permutation. The Cycle class is more flexible than Permutation in
  205. that 1) all elements need not be present in order to investigate how
  206. multiple cycles act in sequence and 2) it can contain singletons:
  207. >>> from sympy.combinatorics.permutations import Perm, Cycle
  208. A Cycle will automatically parse a cycle given as a tuple on the rhs:
  209. >>> Cycle(1, 2)(2, 3)
  210. (1 3 2)
  211. The identity cycle, Cycle(), can be used to start a product:
  212. >>> Cycle()(1, 2)(2, 3)
  213. (1 3 2)
  214. The array form of a Cycle can be obtained by calling the list
  215. method (or passing it to the list function) and all elements from
  216. 0 will be shown:
  217. >>> a = Cycle(1, 2)
  218. >>> a.list()
  219. [0, 2, 1]
  220. >>> list(a)
  221. [0, 2, 1]
  222. If a larger (or smaller) range is desired use the list method and
  223. provide the desired size -- but the Cycle cannot be truncated to
  224. a size smaller than the largest element that is out of place:
  225. >>> b = Cycle(2, 4)(1, 2)(3, 1, 4)(1, 3)
  226. >>> b.list()
  227. [0, 2, 1, 3, 4]
  228. >>> b.list(b.size + 1)
  229. [0, 2, 1, 3, 4, 5]
  230. >>> b.list(-1)
  231. [0, 2, 1]
  232. Singletons are not shown when printing with one exception: the largest
  233. element is always shown -- as a singleton if necessary:
  234. >>> Cycle(1, 4, 10)(4, 5)
  235. (1 5 4 10)
  236. >>> Cycle(1, 2)(4)(5)(10)
  237. (1 2)(10)
  238. The array form can be used to instantiate a Permutation so other
  239. properties of the permutation can be investigated:
  240. >>> Perm(Cycle(1, 2)(3, 4).list()).transpositions()
  241. [(1, 2), (3, 4)]
  242. Notes
  243. =====
  244. The underlying structure of the Cycle is a dictionary and although
  245. the __iter__ method has been redefined to give the array form of the
  246. cycle, the underlying dictionary items are still available with the
  247. such methods as items():
  248. >>> list(Cycle(1, 2).items())
  249. [(1, 2), (2, 1)]
  250. See Also
  251. ========
  252. Permutation
  253. """
  254. def __missing__(self, arg):
  255. """Enter arg into dictionary and return arg."""
  256. return as_int(arg)
  257. def __iter__(self):
  258. yield from self.list()
  259. def __call__(self, *other):
  260. """Return product of cycles processed from R to L.
  261. Examples
  262. ========
  263. >>> from sympy.combinatorics import Cycle
  264. >>> Cycle(1, 2)(2, 3)
  265. (1 3 2)
  266. An instance of a Cycle will automatically parse list-like
  267. objects and Permutations that are on the right. It is more
  268. flexible than the Permutation in that all elements need not
  269. be present:
  270. >>> a = Cycle(1, 2)
  271. >>> a(2, 3)
  272. (1 3 2)
  273. >>> a(2, 3)(4, 5)
  274. (1 3 2)(4 5)
  275. """
  276. rv = Cycle(*other)
  277. for k, v in zip(list(self.keys()), [rv[self[k]] for k in self.keys()]):
  278. rv[k] = v
  279. return rv
  280. def list(self, size=None):
  281. """Return the cycles as an explicit list starting from 0 up
  282. to the greater of the largest value in the cycles and size.
  283. Truncation of trailing unmoved items will occur when size
  284. is less than the maximum element in the cycle; if this is
  285. desired, setting ``size=-1`` will guarantee such trimming.
  286. Examples
  287. ========
  288. >>> from sympy.combinatorics import Cycle
  289. >>> p = Cycle(2, 3)(4, 5)
  290. >>> p.list()
  291. [0, 1, 3, 2, 5, 4]
  292. >>> p.list(10)
  293. [0, 1, 3, 2, 5, 4, 6, 7, 8, 9]
  294. Passing a length too small will trim trailing, unchanged elements
  295. in the permutation:
  296. >>> Cycle(2, 4)(1, 2, 4).list(-1)
  297. [0, 2, 1]
  298. """
  299. if not self and size is None:
  300. raise ValueError('must give size for empty Cycle')
  301. if size is not None:
  302. big = max([i for i in self.keys() if self[i] != i] + [0])
  303. size = max(size, big + 1)
  304. else:
  305. size = self.size
  306. return [self[i] for i in range(size)]
  307. def __repr__(self):
  308. """We want it to print as a Cycle, not as a dict.
  309. Examples
  310. ========
  311. >>> from sympy.combinatorics import Cycle
  312. >>> Cycle(1, 2)
  313. (1 2)
  314. >>> print(_)
  315. (1 2)
  316. >>> list(Cycle(1, 2).items())
  317. [(1, 2), (2, 1)]
  318. """
  319. if not self:
  320. return 'Cycle()'
  321. cycles = Permutation(self).cyclic_form
  322. s = ''.join(str(tuple(c)) for c in cycles)
  323. big = self.size - 1
  324. if not any(i == big for c in cycles for i in c):
  325. s += '(%s)' % big
  326. return 'Cycle%s' % s
  327. def __str__(self):
  328. """We want it to be printed in a Cycle notation with no
  329. comma in-between.
  330. Examples
  331. ========
  332. >>> from sympy.combinatorics import Cycle
  333. >>> Cycle(1, 2)
  334. (1 2)
  335. >>> Cycle(1, 2, 4)(5, 6)
  336. (1 2 4)(5 6)
  337. """
  338. if not self:
  339. return '()'
  340. cycles = Permutation(self).cyclic_form
  341. s = ''.join(str(tuple(c)) for c in cycles)
  342. big = self.size - 1
  343. if not any(i == big for c in cycles for i in c):
  344. s += '(%s)' % big
  345. s = s.replace(',', '')
  346. return s
  347. def __init__(self, *args):
  348. """Load up a Cycle instance with the values for the cycle.
  349. Examples
  350. ========
  351. >>> from sympy.combinatorics import Cycle
  352. >>> Cycle(1, 2, 6)
  353. (1 2 6)
  354. """
  355. if not args:
  356. return
  357. if len(args) == 1:
  358. if isinstance(args[0], Permutation):
  359. for c in args[0].cyclic_form:
  360. self.update(self(*c))
  361. return
  362. elif isinstance(args[0], Cycle):
  363. for k, v in args[0].items():
  364. self[k] = v
  365. return
  366. args = [as_int(a) for a in args]
  367. if any(i < 0 for i in args):
  368. raise ValueError('negative integers are not allowed in a cycle.')
  369. if has_dups(args):
  370. raise ValueError('All elements must be unique in a cycle.')
  371. for i in range(-len(args), 0):
  372. self[args[i]] = args[i + 1]
  373. @property
  374. def size(self):
  375. if not self:
  376. return 0
  377. return max(self.keys()) + 1
  378. def copy(self):
  379. return Cycle(self)
  380. class Permutation(Atom):
  381. r"""
  382. A permutation, alternatively known as an 'arrangement number' or 'ordering'
  383. is an arrangement of the elements of an ordered list into a one-to-one
  384. mapping with itself. The permutation of a given arrangement is given by
  385. indicating the positions of the elements after re-arrangement [2]_. For
  386. example, if one started with elements ``[x, y, a, b]`` (in that order) and
  387. they were reordered as ``[x, y, b, a]`` then the permutation would be
  388. ``[0, 1, 3, 2]``. Notice that (in SymPy) the first element is always referred
  389. to as 0 and the permutation uses the indices of the elements in the
  390. original ordering, not the elements ``(a, b, ...)`` themselves.
  391. >>> from sympy.combinatorics import Permutation
  392. >>> from sympy import init_printing
  393. >>> init_printing(perm_cyclic=False, pretty_print=False)
  394. Permutations Notation
  395. =====================
  396. Permutations are commonly represented in disjoint cycle or array forms.
  397. Array Notation and 2-line Form
  398. ------------------------------------
  399. In the 2-line form, the elements and their final positions are shown
  400. as a matrix with 2 rows:
  401. [0 1 2 ... n-1]
  402. [p(0) p(1) p(2) ... p(n-1)]
  403. Since the first line is always ``range(n)``, where n is the size of p,
  404. it is sufficient to represent the permutation by the second line,
  405. referred to as the "array form" of the permutation. This is entered
  406. in brackets as the argument to the Permutation class:
  407. >>> p = Permutation([0, 2, 1]); p
  408. Permutation([0, 2, 1])
  409. Given i in range(p.size), the permutation maps i to i^p
  410. >>> [i^p for i in range(p.size)]
  411. [0, 2, 1]
  412. The composite of two permutations p*q means first apply p, then q, so
  413. i^(p*q) = (i^p)^q which is i^p^q according to Python precedence rules:
  414. >>> q = Permutation([2, 1, 0])
  415. >>> [i^p^q for i in range(3)]
  416. [2, 0, 1]
  417. >>> [i^(p*q) for i in range(3)]
  418. [2, 0, 1]
  419. One can use also the notation p(i) = i^p, but then the composition
  420. rule is (p*q)(i) = q(p(i)), not p(q(i)):
  421. >>> [(p*q)(i) for i in range(p.size)]
  422. [2, 0, 1]
  423. >>> [q(p(i)) for i in range(p.size)]
  424. [2, 0, 1]
  425. >>> [p(q(i)) for i in range(p.size)]
  426. [1, 2, 0]
  427. Disjoint Cycle Notation
  428. -----------------------
  429. In disjoint cycle notation, only the elements that have shifted are
  430. indicated.
  431. For example, [1, 3, 2, 0] can be represented as (0, 1, 3)(2).
  432. This can be understood from the 2 line format of the given permutation.
  433. In the 2-line form,
  434. [0 1 2 3]
  435. [1 3 2 0]
  436. The element in the 0th position is 1, so 0 -> 1. The element in the 1st
  437. position is three, so 1 -> 3. And the element in the third position is again
  438. 0, so 3 -> 0. Thus, 0 -> 1 -> 3 -> 0, and 2 -> 2. Thus, this can be represented
  439. as 2 cycles: (0, 1, 3)(2).
  440. In common notation, singular cycles are not explicitly written as they can be
  441. inferred implicitly.
  442. Only the relative ordering of elements in a cycle matter:
  443. >>> Permutation(1,2,3) == Permutation(2,3,1) == Permutation(3,1,2)
  444. True
  445. The disjoint cycle notation is convenient when representing
  446. permutations that have several cycles in them:
  447. >>> Permutation(1, 2)(3, 5) == Permutation([[1, 2], [3, 5]])
  448. True
  449. It also provides some economy in entry when computing products of
  450. permutations that are written in disjoint cycle notation:
  451. >>> Permutation(1, 2)(1, 3)(2, 3)
  452. Permutation([0, 3, 2, 1])
  453. >>> _ == Permutation([[1, 2]])*Permutation([[1, 3]])*Permutation([[2, 3]])
  454. True
  455. Caution: when the cycles have common elements between them then the order
  456. in which the permutations are applied matters. This module applies
  457. the permutations from *left to right*.
  458. >>> Permutation(1, 2)(2, 3) == Permutation([(1, 2), (2, 3)])
  459. True
  460. >>> Permutation(1, 2)(2, 3).list()
  461. [0, 3, 1, 2]
  462. In the above case, (1,2) is computed before (2,3).
  463. As 0 -> 0, 0 -> 0, element in position 0 is 0.
  464. As 1 -> 2, 2 -> 3, element in position 1 is 3.
  465. As 2 -> 1, 1 -> 1, element in position 2 is 1.
  466. As 3 -> 3, 3 -> 2, element in position 3 is 2.
  467. If the first and second elements had been
  468. swapped first, followed by the swapping of the second
  469. and third, the result would have been [0, 2, 3, 1].
  470. If, you want to apply the cycles in the conventional
  471. right to left order, call the function with arguments in reverse order
  472. as demonstrated below:
  473. >>> Permutation([(1, 2), (2, 3)][::-1]).list()
  474. [0, 2, 3, 1]
  475. Entering a singleton in a permutation is a way to indicate the size of the
  476. permutation. The ``size`` keyword can also be used.
  477. Array-form entry:
  478. >>> Permutation([[1, 2], [9]])
  479. Permutation([0, 2, 1], size=10)
  480. >>> Permutation([[1, 2]], size=10)
  481. Permutation([0, 2, 1], size=10)
  482. Cyclic-form entry:
  483. >>> Permutation(1, 2, size=10)
  484. Permutation([0, 2, 1], size=10)
  485. >>> Permutation(9)(1, 2)
  486. Permutation([0, 2, 1], size=10)
  487. Caution: no singleton containing an element larger than the largest
  488. in any previous cycle can be entered. This is an important difference
  489. in how Permutation and Cycle handle the ``__call__`` syntax. A singleton
  490. argument at the start of a Permutation performs instantiation of the
  491. Permutation and is permitted:
  492. >>> Permutation(5)
  493. Permutation([], size=6)
  494. A singleton entered after instantiation is a call to the permutation
  495. -- a function call -- and if the argument is out of range it will
  496. trigger an error. For this reason, it is better to start the cycle
  497. with the singleton:
  498. The following fails because there is no element 3:
  499. >>> Permutation(1, 2)(3)
  500. Traceback (most recent call last):
  501. ...
  502. IndexError: list index out of range
  503. This is ok: only the call to an out of range singleton is prohibited;
  504. otherwise the permutation autosizes:
  505. >>> Permutation(3)(1, 2)
  506. Permutation([0, 2, 1, 3])
  507. >>> Permutation(1, 2)(3, 4) == Permutation(3, 4)(1, 2)
  508. True
  509. Equality testing
  510. ----------------
  511. The array forms must be the same in order for permutations to be equal:
  512. >>> Permutation([1, 0, 2, 3]) == Permutation([1, 0])
  513. False
  514. Identity Permutation
  515. --------------------
  516. The identity permutation is a permutation in which no element is out of
  517. place. It can be entered in a variety of ways. All the following create
  518. an identity permutation of size 4:
  519. >>> I = Permutation([0, 1, 2, 3])
  520. >>> all(p == I for p in [
  521. ... Permutation(3),
  522. ... Permutation(range(4)),
  523. ... Permutation([], size=4),
  524. ... Permutation(size=4)])
  525. True
  526. Watch out for entering the range *inside* a set of brackets (which is
  527. cycle notation):
  528. >>> I == Permutation([range(4)])
  529. False
  530. Permutation Printing
  531. ====================
  532. There are a few things to note about how Permutations are printed.
  533. .. deprecated:: 1.6
  534. Configuring Permutation printing by setting
  535. ``Permutation.print_cyclic`` is deprecated. Users should use the
  536. ``perm_cyclic`` flag to the printers, as described below.
  537. 1) If you prefer one form (array or cycle) over another, you can set
  538. ``init_printing`` with the ``perm_cyclic`` flag.
  539. >>> from sympy import init_printing
  540. >>> p = Permutation(1, 2)(4, 5)(3, 4)
  541. >>> p
  542. Permutation([0, 2, 1, 4, 5, 3])
  543. >>> init_printing(perm_cyclic=True, pretty_print=False)
  544. >>> p
  545. (1 2)(3 4 5)
  546. 2) Regardless of the setting, a list of elements in the array for cyclic
  547. form can be obtained and either of those can be copied and supplied as
  548. the argument to Permutation:
  549. >>> p.array_form
  550. [0, 2, 1, 4, 5, 3]
  551. >>> p.cyclic_form
  552. [[1, 2], [3, 4, 5]]
  553. >>> Permutation(_) == p
  554. True
  555. 3) Printing is economical in that as little as possible is printed while
  556. retaining all information about the size of the permutation:
  557. >>> init_printing(perm_cyclic=False, pretty_print=False)
  558. >>> Permutation([1, 0, 2, 3])
  559. Permutation([1, 0, 2, 3])
  560. >>> Permutation([1, 0, 2, 3], size=20)
  561. Permutation([1, 0], size=20)
  562. >>> Permutation([1, 0, 2, 4, 3, 5, 6], size=20)
  563. Permutation([1, 0, 2, 4, 3], size=20)
  564. >>> p = Permutation([1, 0, 2, 3])
  565. >>> init_printing(perm_cyclic=True, pretty_print=False)
  566. >>> p
  567. (3)(0 1)
  568. >>> init_printing(perm_cyclic=False, pretty_print=False)
  569. The 2 was not printed but it is still there as can be seen with the
  570. array_form and size methods:
  571. >>> p.array_form
  572. [1, 0, 2, 3]
  573. >>> p.size
  574. 4
  575. Short introduction to other methods
  576. ===================================
  577. The permutation can act as a bijective function, telling what element is
  578. located at a given position
  579. >>> q = Permutation([5, 2, 3, 4, 1, 0])
  580. >>> q.array_form[1] # the hard way
  581. 2
  582. >>> q(1) # the easy way
  583. 2
  584. >>> {i: q(i) for i in range(q.size)} # showing the bijection
  585. {0: 5, 1: 2, 2: 3, 3: 4, 4: 1, 5: 0}
  586. The full cyclic form (including singletons) can be obtained:
  587. >>> p.full_cyclic_form
  588. [[0, 1], [2], [3]]
  589. Any permutation can be factored into transpositions of pairs of elements:
  590. >>> Permutation([[1, 2], [3, 4, 5]]).transpositions()
  591. [(1, 2), (3, 5), (3, 4)]
  592. >>> Permutation.rmul(*[Permutation([ti], size=6) for ti in _]).cyclic_form
  593. [[1, 2], [3, 4, 5]]
  594. The number of permutations on a set of n elements is given by n! and is
  595. called the cardinality.
  596. >>> p.size
  597. 4
  598. >>> p.cardinality
  599. 24
  600. A given permutation has a rank among all the possible permutations of the
  601. same elements, but what that rank is depends on how the permutations are
  602. enumerated. (There are a number of different methods of doing so.) The
  603. lexicographic rank is given by the rank method and this rank is used to
  604. increment a permutation with addition/subtraction:
  605. >>> p.rank()
  606. 6
  607. >>> p + 1
  608. Permutation([1, 0, 3, 2])
  609. >>> p.next_lex()
  610. Permutation([1, 0, 3, 2])
  611. >>> _.rank()
  612. 7
  613. >>> p.unrank_lex(p.size, rank=7)
  614. Permutation([1, 0, 3, 2])
  615. The product of two permutations p and q is defined as their composition as
  616. functions, (p*q)(i) = q(p(i)) [6]_.
  617. >>> p = Permutation([1, 0, 2, 3])
  618. >>> q = Permutation([2, 3, 1, 0])
  619. >>> list(q*p)
  620. [2, 3, 0, 1]
  621. >>> list(p*q)
  622. [3, 2, 1, 0]
  623. >>> [q(p(i)) for i in range(p.size)]
  624. [3, 2, 1, 0]
  625. The permutation can be 'applied' to any list-like object, not only
  626. Permutations:
  627. >>> p(['zero', 'one', 'four', 'two'])
  628. ['one', 'zero', 'four', 'two']
  629. >>> p('zo42')
  630. ['o', 'z', '4', '2']
  631. If you have a list of arbitrary elements, the corresponding permutation
  632. can be found with the from_sequence method:
  633. >>> Permutation.from_sequence('SymPy')
  634. Permutation([1, 3, 2, 0, 4])
  635. Checking if a Permutation is contained in a Group
  636. =================================================
  637. Generally if you have a group of permutations G on n symbols, and
  638. you're checking if a permutation on less than n symbols is part
  639. of that group, the check will fail.
  640. Here is an example for n=5 and we check if the cycle
  641. (1,2,3) is in G:
  642. >>> from sympy import init_printing
  643. >>> init_printing(perm_cyclic=True, pretty_print=False)
  644. >>> from sympy.combinatorics import Cycle, Permutation
  645. >>> from sympy.combinatorics.perm_groups import PermutationGroup
  646. >>> G = PermutationGroup(Cycle(2, 3)(4, 5), Cycle(1, 2, 3, 4, 5))
  647. >>> p1 = Permutation(Cycle(2, 5, 3))
  648. >>> p2 = Permutation(Cycle(1, 2, 3))
  649. >>> a1 = Permutation(Cycle(1, 2, 3).list(6))
  650. >>> a2 = Permutation(Cycle(1, 2, 3)(5))
  651. >>> a3 = Permutation(Cycle(1, 2, 3),size=6)
  652. >>> for p in [p1,p2,a1,a2,a3]: p, G.contains(p)
  653. ((2 5 3), True)
  654. ((1 2 3), False)
  655. ((5)(1 2 3), True)
  656. ((5)(1 2 3), True)
  657. ((5)(1 2 3), True)
  658. The check for p2 above will fail.
  659. Checking if p1 is in G works because SymPy knows
  660. G is a group on 5 symbols, and p1 is also on 5 symbols
  661. (its largest element is 5).
  662. For ``a1``, the ``.list(6)`` call will extend the permutation to 5
  663. symbols, so the test will work as well. In the case of ``a2`` the
  664. permutation is being extended to 5 symbols by using a singleton,
  665. and in the case of ``a3`` it's extended through the constructor
  666. argument ``size=6``.
  667. There is another way to do this, which is to tell the ``contains``
  668. method that the number of symbols the group is on doesn't need to
  669. match perfectly the number of symbols for the permutation:
  670. >>> G.contains(p2,strict=False)
  671. True
  672. This can be via the ``strict`` argument to the ``contains`` method,
  673. and SymPy will try to extend the permutation on its own and then
  674. perform the containment check.
  675. See Also
  676. ========
  677. Cycle
  678. References
  679. ==========
  680. .. [1] Skiena, S. 'Permutations.' 1.1 in Implementing Discrete Mathematics
  681. Combinatorics and Graph Theory with Mathematica. Reading, MA:
  682. Addison-Wesley, pp. 3-16, 1990.
  683. .. [2] Knuth, D. E. The Art of Computer Programming, Vol. 4: Combinatorial
  684. Algorithms, 1st ed. Reading, MA: Addison-Wesley, 2011.
  685. .. [3] Wendy Myrvold and Frank Ruskey. 2001. Ranking and unranking
  686. permutations in linear time. Inf. Process. Lett. 79, 6 (September 2001),
  687. 281-284. DOI=10.1016/S0020-0190(01)00141-7
  688. .. [4] D. L. Kreher, D. R. Stinson 'Combinatorial Algorithms'
  689. CRC Press, 1999
  690. .. [5] Graham, R. L.; Knuth, D. E.; and Patashnik, O.
  691. Concrete Mathematics: A Foundation for Computer Science, 2nd ed.
  692. Reading, MA: Addison-Wesley, 1994.
  693. .. [6] https://en.wikipedia.org/wiki/Permutation#Product_and_inverse
  694. .. [7] https://en.wikipedia.org/wiki/Lehmer_code
  695. """
  696. is_Permutation = True
  697. _array_form = None
  698. _cyclic_form = None
  699. _cycle_structure = None
  700. _size = None
  701. _rank = None
  702. def __new__(cls, *args, size=None, **kwargs):
  703. """
  704. Constructor for the Permutation object from a list or a
  705. list of lists in which all elements of the permutation may
  706. appear only once.
  707. Examples
  708. ========
  709. >>> from sympy.combinatorics import Permutation
  710. >>> from sympy import init_printing
  711. >>> init_printing(perm_cyclic=False, pretty_print=False)
  712. Permutations entered in array-form are left unaltered:
  713. >>> Permutation([0, 2, 1])
  714. Permutation([0, 2, 1])
  715. Permutations entered in cyclic form are converted to array form;
  716. singletons need not be entered, but can be entered to indicate the
  717. largest element:
  718. >>> Permutation([[4, 5, 6], [0, 1]])
  719. Permutation([1, 0, 2, 3, 5, 6, 4])
  720. >>> Permutation([[4, 5, 6], [0, 1], [19]])
  721. Permutation([1, 0, 2, 3, 5, 6, 4], size=20)
  722. All manipulation of permutations assumes that the smallest element
  723. is 0 (in keeping with 0-based indexing in Python) so if the 0 is
  724. missing when entering a permutation in array form, an error will be
  725. raised:
  726. >>> Permutation([2, 1])
  727. Traceback (most recent call last):
  728. ...
  729. ValueError: Integers 0 through 2 must be present.
  730. If a permutation is entered in cyclic form, it can be entered without
  731. singletons and the ``size`` specified so those values can be filled
  732. in, otherwise the array form will only extend to the maximum value
  733. in the cycles:
  734. >>> Permutation([[1, 4], [3, 5, 2]], size=10)
  735. Permutation([0, 4, 3, 5, 1, 2], size=10)
  736. >>> _.array_form
  737. [0, 4, 3, 5, 1, 2, 6, 7, 8, 9]
  738. """
  739. if size is not None:
  740. size = int(size)
  741. #a) ()
  742. #b) (1) = identity
  743. #c) (1, 2) = cycle
  744. #d) ([1, 2, 3]) = array form
  745. #e) ([[1, 2]]) = cyclic form
  746. #f) (Cycle) = conversion to permutation
  747. #g) (Permutation) = adjust size or return copy
  748. ok = True
  749. if not args: # a
  750. return cls._af_new(list(range(size or 0)))
  751. elif len(args) > 1: # c
  752. return cls._af_new(Cycle(*args).list(size))
  753. if len(args) == 1:
  754. a = args[0]
  755. if isinstance(a, cls): # g
  756. if size is None or size == a.size:
  757. return a
  758. return cls(a.array_form, size=size)
  759. if isinstance(a, Cycle): # f
  760. return cls._af_new(a.list(size))
  761. if not is_sequence(a): # b
  762. if size is not None and a + 1 > size:
  763. raise ValueError('size is too small when max is %s' % a)
  764. return cls._af_new(list(range(a + 1)))
  765. if has_variety(is_sequence(ai) for ai in a):
  766. ok = False
  767. else:
  768. ok = False
  769. if not ok:
  770. raise ValueError("Permutation argument must be a list of ints, "
  771. "a list of lists, Permutation or Cycle.")
  772. # safe to assume args are valid; this also makes a copy
  773. # of the args
  774. args = list(args[0])
  775. is_cycle = args and is_sequence(args[0])
  776. if is_cycle: # e
  777. args = [[int(i) for i in c] for c in args]
  778. else: # d
  779. args = [int(i) for i in args]
  780. # if there are n elements present, 0, 1, ..., n-1 should be present
  781. # unless a cycle notation has been provided. A 0 will be added
  782. # for convenience in case one wants to enter permutations where
  783. # counting starts from 1.
  784. temp = flatten(args)
  785. if has_dups(temp) and not is_cycle:
  786. raise ValueError('there were repeated elements.')
  787. temp = set(temp)
  788. if not is_cycle:
  789. if temp != set(range(len(temp))):
  790. raise ValueError('Integers 0 through %s must be present.' %
  791. max(temp))
  792. if size is not None and temp and max(temp) + 1 > size:
  793. raise ValueError('max element should not exceed %s' % (size - 1))
  794. if is_cycle:
  795. # it's not necessarily canonical so we won't store
  796. # it -- use the array form instead
  797. c = Cycle()
  798. for ci in args:
  799. c = c(*ci)
  800. aform = c.list()
  801. else:
  802. aform = list(args)
  803. if size and size > len(aform):
  804. # don't allow for truncation of permutation which
  805. # might split a cycle and lead to an invalid aform
  806. # but do allow the permutation size to be increased
  807. aform.extend(list(range(len(aform), size)))
  808. return cls._af_new(aform)
  809. @classmethod
  810. def _af_new(cls, perm):
  811. """A method to produce a Permutation object from a list;
  812. the list is bound to the _array_form attribute, so it must
  813. not be modified; this method is meant for internal use only;
  814. the list ``a`` is supposed to be generated as a temporary value
  815. in a method, so p = Perm._af_new(a) is the only object
  816. to hold a reference to ``a``::
  817. Examples
  818. ========
  819. >>> from sympy.combinatorics.permutations import Perm
  820. >>> from sympy import init_printing
  821. >>> init_printing(perm_cyclic=False, pretty_print=False)
  822. >>> a = [2, 1, 3, 0]
  823. >>> p = Perm._af_new(a)
  824. >>> p
  825. Permutation([2, 1, 3, 0])
  826. """
  827. p = super().__new__(cls)
  828. p._array_form = perm
  829. p._size = len(perm)
  830. return p
  831. def _hashable_content(self):
  832. # the array_form (a list) is the Permutation arg, so we need to
  833. # return a tuple, instead
  834. return tuple(self.array_form)
  835. @property
  836. def array_form(self):
  837. """
  838. Return a copy of the attribute _array_form
  839. Examples
  840. ========
  841. >>> from sympy.combinatorics import Permutation
  842. >>> p = Permutation([[2, 0], [3, 1]])
  843. >>> p.array_form
  844. [2, 3, 0, 1]
  845. >>> Permutation([[2, 0, 3, 1]]).array_form
  846. [3, 2, 0, 1]
  847. >>> Permutation([2, 0, 3, 1]).array_form
  848. [2, 0, 3, 1]
  849. >>> Permutation([[1, 2], [4, 5]]).array_form
  850. [0, 2, 1, 3, 5, 4]
  851. """
  852. return self._array_form[:]
  853. def list(self, size=None):
  854. """Return the permutation as an explicit list, possibly
  855. trimming unmoved elements if size is less than the maximum
  856. element in the permutation; if this is desired, setting
  857. ``size=-1`` will guarantee such trimming.
  858. Examples
  859. ========
  860. >>> from sympy.combinatorics import Permutation
  861. >>> p = Permutation(2, 3)(4, 5)
  862. >>> p.list()
  863. [0, 1, 3, 2, 5, 4]
  864. >>> p.list(10)
  865. [0, 1, 3, 2, 5, 4, 6, 7, 8, 9]
  866. Passing a length too small will trim trailing, unchanged elements
  867. in the permutation:
  868. >>> Permutation(2, 4)(1, 2, 4).list(-1)
  869. [0, 2, 1]
  870. >>> Permutation(3).list(-1)
  871. []
  872. """
  873. if not self and size is None:
  874. raise ValueError('must give size for empty Cycle')
  875. rv = self.array_form
  876. if size is not None:
  877. if size > self.size:
  878. rv.extend(list(range(self.size, size)))
  879. else:
  880. # find first value from rhs where rv[i] != i
  881. i = self.size - 1
  882. while rv:
  883. if rv[-1] != i:
  884. break
  885. rv.pop()
  886. i -= 1
  887. return rv
  888. @property
  889. def cyclic_form(self):
  890. """
  891. This is used to convert to the cyclic notation
  892. from the canonical notation. Singletons are omitted.
  893. Examples
  894. ========
  895. >>> from sympy.combinatorics import Permutation
  896. >>> p = Permutation([0, 3, 1, 2])
  897. >>> p.cyclic_form
  898. [[1, 3, 2]]
  899. >>> Permutation([1, 0, 2, 4, 3, 5]).cyclic_form
  900. [[0, 1], [3, 4]]
  901. See Also
  902. ========
  903. array_form, full_cyclic_form
  904. """
  905. if self._cyclic_form is not None:
  906. return list(self._cyclic_form)
  907. array_form = self.array_form
  908. unchecked = [True] * len(array_form)
  909. cyclic_form = []
  910. for i in range(len(array_form)):
  911. if unchecked[i]:
  912. cycle = []
  913. cycle.append(i)
  914. unchecked[i] = False
  915. j = i
  916. while unchecked[array_form[j]]:
  917. j = array_form[j]
  918. cycle.append(j)
  919. unchecked[j] = False
  920. if len(cycle) > 1:
  921. cyclic_form.append(cycle)
  922. assert cycle == list(minlex(cycle))
  923. cyclic_form.sort()
  924. self._cyclic_form = cyclic_form[:]
  925. return cyclic_form
  926. @property
  927. def full_cyclic_form(self):
  928. """Return permutation in cyclic form including singletons.
  929. Examples
  930. ========
  931. >>> from sympy.combinatorics import Permutation
  932. >>> Permutation([0, 2, 1]).full_cyclic_form
  933. [[0], [1, 2]]
  934. """
  935. need = set(range(self.size)) - set(flatten(self.cyclic_form))
  936. rv = self.cyclic_form + [[i] for i in need]
  937. rv.sort()
  938. return rv
  939. @property
  940. def size(self):
  941. """
  942. Returns the number of elements in the permutation.
  943. Examples
  944. ========
  945. >>> from sympy.combinatorics import Permutation
  946. >>> Permutation([[3, 2], [0, 1]]).size
  947. 4
  948. See Also
  949. ========
  950. cardinality, length, order, rank
  951. """
  952. return self._size
  953. def support(self):
  954. """Return the elements in permutation, P, for which P[i] != i.
  955. Examples
  956. ========
  957. >>> from sympy.combinatorics import Permutation
  958. >>> p = Permutation([[3, 2], [0, 1], [4]])
  959. >>> p.array_form
  960. [1, 0, 3, 2, 4]
  961. >>> p.support()
  962. [0, 1, 2, 3]
  963. """
  964. a = self.array_form
  965. return [i for i, e in enumerate(a) if a[i] != i]
  966. def __add__(self, other):
  967. """Return permutation that is other higher in rank than self.
  968. The rank is the lexicographical rank, with the identity permutation
  969. having rank of 0.
  970. Examples
  971. ========
  972. >>> from sympy.combinatorics import Permutation
  973. >>> I = Permutation([0, 1, 2, 3])
  974. >>> a = Permutation([2, 1, 3, 0])
  975. >>> I + a.rank() == a
  976. True
  977. See Also
  978. ========
  979. __sub__, inversion_vector
  980. """
  981. rank = (self.rank() + other) % self.cardinality
  982. rv = self.unrank_lex(self.size, rank)
  983. rv._rank = rank
  984. return rv
  985. def __sub__(self, other):
  986. """Return the permutation that is other lower in rank than self.
  987. See Also
  988. ========
  989. __add__
  990. """
  991. return self.__add__(-other)
  992. @staticmethod
  993. def rmul(*args):
  994. """
  995. Return product of Permutations [a, b, c, ...] as the Permutation whose
  996. ith value is a(b(c(i))).
  997. a, b, c, ... can be Permutation objects or tuples.
  998. Examples
  999. ========
  1000. >>> from sympy.combinatorics import Permutation
  1001. >>> a, b = [1, 0, 2], [0, 2, 1]
  1002. >>> a = Permutation(a); b = Permutation(b)
  1003. >>> list(Permutation.rmul(a, b))
  1004. [1, 2, 0]
  1005. >>> [a(b(i)) for i in range(3)]
  1006. [1, 2, 0]
  1007. This handles the operands in reverse order compared to the ``*`` operator:
  1008. >>> a = Permutation(a); b = Permutation(b)
  1009. >>> list(a*b)
  1010. [2, 0, 1]
  1011. >>> [b(a(i)) for i in range(3)]
  1012. [2, 0, 1]
  1013. Notes
  1014. =====
  1015. All items in the sequence will be parsed by Permutation as
  1016. necessary as long as the first item is a Permutation:
  1017. >>> Permutation.rmul(a, [0, 2, 1]) == Permutation.rmul(a, b)
  1018. True
  1019. The reverse order of arguments will raise a TypeError.
  1020. """
  1021. rv = args[0]
  1022. for i in range(1, len(args)):
  1023. rv = args[i]*rv
  1024. return rv
  1025. @classmethod
  1026. def rmul_with_af(cls, *args):
  1027. """
  1028. same as rmul, but the elements of args are Permutation objects
  1029. which have _array_form
  1030. """
  1031. a = [x._array_form for x in args]
  1032. rv = cls._af_new(_af_rmuln(*a))
  1033. return rv
  1034. def mul_inv(self, other):
  1035. """
  1036. other*~self, self and other have _array_form
  1037. """
  1038. a = _af_invert(self._array_form)
  1039. b = other._array_form
  1040. return self._af_new(_af_rmul(a, b))
  1041. def __rmul__(self, other):
  1042. """This is needed to coerce other to Permutation in rmul."""
  1043. cls = type(self)
  1044. return cls(other)*self
  1045. def __mul__(self, other):
  1046. """
  1047. Return the product a*b as a Permutation; the ith value is b(a(i)).
  1048. Examples
  1049. ========
  1050. >>> from sympy.combinatorics.permutations import _af_rmul, Permutation
  1051. >>> a, b = [1, 0, 2], [0, 2, 1]
  1052. >>> a = Permutation(a); b = Permutation(b)
  1053. >>> list(a*b)
  1054. [2, 0, 1]
  1055. >>> [b(a(i)) for i in range(3)]
  1056. [2, 0, 1]
  1057. This handles operands in reverse order compared to _af_rmul and rmul:
  1058. >>> al = list(a); bl = list(b)
  1059. >>> _af_rmul(al, bl)
  1060. [1, 2, 0]
  1061. >>> [al[bl[i]] for i in range(3)]
  1062. [1, 2, 0]
  1063. It is acceptable for the arrays to have different lengths; the shorter
  1064. one will be padded to match the longer one:
  1065. >>> from sympy import init_printing
  1066. >>> init_printing(perm_cyclic=False, pretty_print=False)
  1067. >>> b*Permutation([1, 0])
  1068. Permutation([1, 2, 0])
  1069. >>> Permutation([1, 0])*b
  1070. Permutation([2, 0, 1])
  1071. It is also acceptable to allow coercion to handle conversion of a
  1072. single list to the left of a Permutation:
  1073. >>> [0, 1]*a # no change: 2-element identity
  1074. Permutation([1, 0, 2])
  1075. >>> [[0, 1]]*a # exchange first two elements
  1076. Permutation([0, 1, 2])
  1077. You cannot use more than 1 cycle notation in a product of cycles
  1078. since coercion can only handle one argument to the left. To handle
  1079. multiple cycles it is convenient to use Cycle instead of Permutation:
  1080. >>> [[1, 2]]*[[2, 3]]*Permutation([]) # doctest: +SKIP
  1081. >>> from sympy.combinatorics.permutations import Cycle
  1082. >>> Cycle(1, 2)(2, 3)
  1083. (1 3 2)
  1084. """
  1085. from sympy.combinatorics.perm_groups import PermutationGroup, Coset
  1086. if isinstance(other, PermutationGroup):
  1087. return Coset(self, other, dir='-')
  1088. a = self.array_form
  1089. # __rmul__ makes sure the other is a Permutation
  1090. b = other.array_form
  1091. if not b:
  1092. perm = a
  1093. else:
  1094. b.extend(list(range(len(b), len(a))))
  1095. perm = [b[i] for i in a] + b[len(a):]
  1096. return self._af_new(perm)
  1097. def commutes_with(self, other):
  1098. """
  1099. Checks if the elements are commuting.
  1100. Examples
  1101. ========
  1102. >>> from sympy.combinatorics import Permutation
  1103. >>> a = Permutation([1, 4, 3, 0, 2, 5])
  1104. >>> b = Permutation([0, 1, 2, 3, 4, 5])
  1105. >>> a.commutes_with(b)
  1106. True
  1107. >>> b = Permutation([2, 3, 5, 4, 1, 0])
  1108. >>> a.commutes_with(b)
  1109. False
  1110. """
  1111. a = self.array_form
  1112. b = other.array_form
  1113. return _af_commutes_with(a, b)
  1114. def __pow__(self, n):
  1115. """
  1116. Routine for finding powers of a permutation.
  1117. Examples
  1118. ========
  1119. >>> from sympy.combinatorics import Permutation
  1120. >>> from sympy import init_printing
  1121. >>> init_printing(perm_cyclic=False, pretty_print=False)
  1122. >>> p = Permutation([2, 0, 3, 1])
  1123. >>> p.order()
  1124. 4
  1125. >>> p**4
  1126. Permutation([0, 1, 2, 3])
  1127. """
  1128. if isinstance(n, Permutation):
  1129. raise NotImplementedError(
  1130. 'p**p is not defined; do you mean p^p (conjugate)?')
  1131. n = int(n)
  1132. return self._af_new(_af_pow(self.array_form, n))
  1133. def __rxor__(self, i):
  1134. """Return self(i) when ``i`` is an int.
  1135. Examples
  1136. ========
  1137. >>> from sympy.combinatorics import Permutation
  1138. >>> p = Permutation(1, 2, 9)
  1139. >>> 2^p == p(2) == 9
  1140. True
  1141. """
  1142. if int(i) == i:
  1143. return self(i)
  1144. else:
  1145. raise NotImplementedError(
  1146. "i^p = p(i) when i is an integer, not %s." % i)
  1147. def __xor__(self, h):
  1148. """Return the conjugate permutation ``~h*self*h` `.
  1149. Explanation
  1150. ===========
  1151. If ``a`` and ``b`` are conjugates, ``a = h*b*~h`` and
  1152. ``b = ~h*a*h`` and both have the same cycle structure.
  1153. Examples
  1154. ========
  1155. >>> from sympy.combinatorics import Permutation
  1156. >>> p = Permutation(1, 2, 9)
  1157. >>> q = Permutation(6, 9, 8)
  1158. >>> p*q != q*p
  1159. True
  1160. Calculate and check properties of the conjugate:
  1161. >>> c = p^q
  1162. >>> c == ~q*p*q and p == q*c*~q
  1163. True
  1164. The expression q^p^r is equivalent to q^(p*r):
  1165. >>> r = Permutation(9)(4, 6, 8)
  1166. >>> q^p^r == q^(p*r)
  1167. True
  1168. If the term to the left of the conjugate operator, i, is an integer
  1169. then this is interpreted as selecting the ith element from the
  1170. permutation to the right:
  1171. >>> all(i^p == p(i) for i in range(p.size))
  1172. True
  1173. Note that the * operator as higher precedence than the ^ operator:
  1174. >>> q^r*p^r == q^(r*p)^r == Permutation(9)(1, 6, 4)
  1175. True
  1176. Notes
  1177. =====
  1178. In Python the precedence rule is p^q^r = (p^q)^r which differs
  1179. in general from p^(q^r)
  1180. >>> q^p^r
  1181. (9)(1 4 8)
  1182. >>> q^(p^r)
  1183. (9)(1 8 6)
  1184. For a given r and p, both of the following are conjugates of p:
  1185. ~r*p*r and r*p*~r. But these are not necessarily the same:
  1186. >>> ~r*p*r == r*p*~r
  1187. True
  1188. >>> p = Permutation(1, 2, 9)(5, 6)
  1189. >>> ~r*p*r == r*p*~r
  1190. False
  1191. The conjugate ~r*p*r was chosen so that ``p^q^r`` would be equivalent
  1192. to ``p^(q*r)`` rather than ``p^(r*q)``. To obtain r*p*~r, pass ~r to
  1193. this method:
  1194. >>> p^~r == r*p*~r
  1195. True
  1196. """
  1197. if self.size != h.size:
  1198. raise ValueError("The permutations must be of equal size.")
  1199. a = [None]*self.size
  1200. h = h._array_form
  1201. p = self._array_form
  1202. for i in range(self.size):
  1203. a[h[i]] = h[p[i]]
  1204. return self._af_new(a)
  1205. def transpositions(self):
  1206. """
  1207. Return the permutation decomposed into a list of transpositions.
  1208. Explanation
  1209. ===========
  1210. It is always possible to express a permutation as the product of
  1211. transpositions, see [1]
  1212. Examples
  1213. ========
  1214. >>> from sympy.combinatorics import Permutation
  1215. >>> p = Permutation([[1, 2, 3], [0, 4, 5, 6, 7]])
  1216. >>> t = p.transpositions()
  1217. >>> t
  1218. [(0, 7), (0, 6), (0, 5), (0, 4), (1, 3), (1, 2)]
  1219. >>> print(''.join(str(c) for c in t))
  1220. (0, 7)(0, 6)(0, 5)(0, 4)(1, 3)(1, 2)
  1221. >>> Permutation.rmul(*[Permutation([ti], size=p.size) for ti in t]) == p
  1222. True
  1223. References
  1224. ==========
  1225. .. [1] https://en.wikipedia.org/wiki/Transposition_%28mathematics%29#Properties
  1226. """
  1227. a = self.cyclic_form
  1228. res = []
  1229. for x in a:
  1230. nx = len(x)
  1231. if nx == 2:
  1232. res.append(tuple(x))
  1233. elif nx > 2:
  1234. first = x[0]
  1235. for y in x[nx - 1:0:-1]:
  1236. res.append((first, y))
  1237. return res
  1238. @classmethod
  1239. def from_sequence(self, i, key=None):
  1240. """Return the permutation needed to obtain ``i`` from the sorted
  1241. elements of ``i``. If custom sorting is desired, a key can be given.
  1242. Examples
  1243. ========
  1244. >>> from sympy.combinatorics import Permutation
  1245. >>> Permutation.from_sequence('SymPy')
  1246. (4)(0 1 3)
  1247. >>> _(sorted("SymPy"))
  1248. ['S', 'y', 'm', 'P', 'y']
  1249. >>> Permutation.from_sequence('SymPy', key=lambda x: x.lower())
  1250. (4)(0 2)(1 3)
  1251. """
  1252. ic = list(zip(i, list(range(len(i)))))
  1253. if key:
  1254. ic.sort(key=lambda x: key(x[0]))
  1255. else:
  1256. ic.sort()
  1257. return ~Permutation([i[1] for i in ic])
  1258. def __invert__(self):
  1259. """
  1260. Return the inverse of the permutation.
  1261. A permutation multiplied by its inverse is the identity permutation.
  1262. Examples
  1263. ========
  1264. >>> from sympy.combinatorics import Permutation
  1265. >>> from sympy import init_printing
  1266. >>> init_printing(perm_cyclic=False, pretty_print=False)
  1267. >>> p = Permutation([[2, 0], [3, 1]])
  1268. >>> ~p
  1269. Permutation([2, 3, 0, 1])
  1270. >>> _ == p**-1
  1271. True
  1272. >>> p*~p == ~p*p == Permutation([0, 1, 2, 3])
  1273. True
  1274. """
  1275. return self._af_new(_af_invert(self._array_form))
  1276. def __iter__(self):
  1277. """Yield elements from array form.
  1278. Examples
  1279. ========
  1280. >>> from sympy.combinatorics import Permutation
  1281. >>> list(Permutation(range(3)))
  1282. [0, 1, 2]
  1283. """
  1284. yield from self.array_form
  1285. def __repr__(self):
  1286. from sympy.printing.repr import srepr
  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 attatching 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] http://www.cp.eng.chula.ac.th/~piak/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] 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