
    \hV                       S SK r S SKJr  S SKJr  S SKJr  S SKJr  S SK	J
r
  S SKJr  S SKJr  S S	KJr  S S
KJr  S SKJr  S SKJr  S SKJr  S SKJrJrJrJrJrJr  S SKJ r   S SK!J"r"  S SK#J$r$  S r%S r&S r'S r(S r)S r* " S S\+5      r, " S S\
5      r-S r.\-r/\/R`                  r0 " S S\5      r1\$" \-\-5      S 5       r2g)     N)defaultdict)Iterable)reduce)global_parameters)Atom)Expr)
int_valued)Integer)_sympify)zeros)lcmsrepr)flattenhas_varietyminlexhas_dupsrunsis_sequenceas_int)ifac)dispatchc                 6    U Vs/ s H  o U   PM	     sn$ s  snf )a  
Return the product b*a; input and output are array forms. The ith value
is a[b[i]].

Examples
========

>>> from sympy.combinatorics.permutations import _af_rmul, Permutation

>>> a, b = [1, 0, 2], [0, 2, 1]
>>> _af_rmul(a, b)
[1, 2, 0]
>>> [a[b[i]] for i in range(3)]
[1, 2, 0]

This handles the operands in reverse order compared to the ``*`` operator:

>>> a = Permutation(a)
>>> b = Permutation(b)
>>> list(a*b)
[2, 0, 1]
>>> [b(a(i)) for i in range(3)]
[2, 0, 1]

See Also
========

rmul, _af_rmuln
 )abis      X/var/www/auris/envauris/lib/python3.13/site-packages/sympy/combinatorics/permutations.py_af_rmulr       s    < !QaD!s   c                  :   U n[        U5      nUS:X  a  Uu  p4nU Vs/ s H	  ocXF      PM     sn$ US:X  a  Uu  p4pWU Vs/ s H  ocXEU         PM     sn$ US:X  a"  Uu  p4pWnU Vs/ s H  ocXEXv            PM     sn$ US:X  a%  Uu  p4pWpU	 Vs/ s H  ocXEXxU               PM     sn$ US:X  a(  Uu  p4pWpn
U
 Vs/ s H  ocXEXxX                  PM     sn$ US:X  a+  Uu  p4pWppU Vs/ s H  ocXEXxXU                     PM     sn$ US:X  a  US   S	S	 $ US
:X  a  Uu  pU Vs/ s H  oaU   PM	     sn$ US:X  a  [        S5      e[        US	US
-   6 n[        XS
-  S	 6 nU Vs/ s H  ocU   PM	     sn$ s  snf s  snf s  snf s  snf s  snf s  snf s  snf s  snf )a  
Given [a, b, c, ...] return the product of ...*c*b*a using array forms.
The ith value is a[b[c[i]]].

Examples
========

>>> from sympy.combinatorics.permutations import _af_rmul, Permutation

>>> a, b = [1, 0, 2], [0, 2, 1]
>>> _af_rmul(a, b)
[1, 2, 0]
>>> [a[b[i]] for i in range(3)]
[1, 2, 0]

This handles the operands in reverse order compared to the ``*`` operator:

>>> a = Permutation(a); b = Permutation(b)
>>> list(a*b)
[2, 0, 1]
>>> [b(a(i)) for i in range(3)]
[2, 0, 1]

See Also
========

rmul, _af_rmul
                     r   N   zString must not be empty)len
ValueError	_af_rmuln)abcr   mp0p1p2r   p3p4p5p6p7r   s                r   r,   r,   6   s   : 	AAAAv
#%&2a25	2&&Av')*r!2e9r**Av+-.2a2i=!2..Av!"/12r!2qEm$%r22Av%&"3562a2ruI'()266Av)*&79:r!2rQ%yM*+,-r::AvtAwAv a!a  Av344	Aeq!tH	B	AdeH	B2aqE23 ' + / 3 7 ;
 !
 s.   E5E:%E?F9F	'F#F$Fc                     [        U 5      nS/U-  nSn[        U5       H4  nX$   S:X  d  M  US-  nSX$'   UnX   U:w  d  M"  X   nSX%'   X   U:w  a  M  M6     X-
  S-  $ )a  
Computes the parity of a permutation in array form.

Explanation
===========

The parity of a permutation reflects the parity of the
number of inversions in the permutation, i.e., the
number of pairs of x and y such that x > y but p[x] < p[y].

Examples
========

>>> from sympy.combinatorics.permutations import _af_parity
>>> _af_parity([0, 1, 2, 3])
0
>>> _af_parity([3, 2, 0, 1])
1

See Also
========

Permutation
r   r(   r)   )r*   range)pinr   cjr   s         r   
_af_parityr=   s   sy    2 	BA	
aA	A1X419FAADA%1*E %1*  EQ;    c                 T    S/[        U 5      -  n[        U 5       H	  u  p#X!U'   M     U$ )a  
Finds the inverse, ~A, of a permutation, A, given in array form.

Examples
========

>>> from sympy.combinatorics.permutations import _af_invert, _af_rmul
>>> A = [1, 2, 0, 3]
>>> _af_invert(A)
[2, 0, 1, 3]
>>> _af_rmul(_, A)
[0, 1, 2, 3]

See Also
========

Permutation, __invert__
r   )r*   	enumerate)r   inv_formr   ais       r   
_af_invertrC      s/    & sSV|H1 Or>   c                    US:X  a  [        [        [        U 5      5      5      $ US:  a  [        [	        U 5      U* 5      $ US:X  a  U SS $ US:X  a  U  Vs/ s H  o U   PM	     nnU$ US:X  a  U  Vs/ s H	  o X      PM     nnU$ US:X  a  U  Vs/ s H  o X U         PM     nnU$ [        [        [        U 5      5      5      n US-  (       a#  U  Vs/ s H  o#U   PM	     nnUS-  nU(       d   U$ US-  S:X  a  U  Vs/ s H  o X U         PM     n nUS-  nO"US-  S:X  a  U  Vs/ s H  o U   PM	     n nUS-  nMy  s  snf s  snf s  snf s  snf s  snf s  snf )a  
Routine for finding powers of a permutation.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.permutations import _af_pow
>>> p = Permutation([2, 0, 3, 1])
>>> p.order()
4
>>> _af_pow(p._array_form, 4)
[0, 1, 2, 3]
r   r(   Nr)   r"   r#   )listr8   r*   _af_powrC   )r   r:   r   r   s       r   rF   rF      s    	AvE#a&M""1uz!}qb))Avt	
a1aqT1( H' 
a aqtWa $ H# 
a!"#Aq1wZ#  H s1v1u#$%1aqT1%Q H 1uz)*+Aq1wZ+FQ!#$%1aqT1%F   # &
 , &s$   D=1EEE>E&Ec                 f   ^ ^ [        U U4S j[        [        T 5      S-
  5       5       5      (       + $ )a  
Checks if the two permutations with array forms
given by ``a`` and ``b`` commute.

Examples
========

>>> from sympy.combinatorics.permutations import _af_commutes_with
>>> _af_commutes_with([1, 2, 0], [0, 2, 1])
False

See Also
========

Permutation, commutes_with
c              3   F   >#    U  H  nTTU      TTU      :g  v   M     g 7fNr   .0r   r   r   s     r   	<genexpr>$_af_commutes_with.<locals>.<genexpr>   s(     A/@!1QqT7a!g%/@s   !r(   )anyr8   r*   )r   r   s   ``r   _af_commutes_withrO      s&    " AuSVaZ/@AAAAr>   c                   \    \ rS rSrSrS rS rS rSS jrS r	S	 r
S
 r\S 5       rS rSrg)Cycle   a_  
Wrapper around dict which provides the functionality of a disjoint cycle.

Explanation
===========

A cycle shows the rule to use to move subsets of elements to obtain
a permutation. The Cycle class is more flexible than Permutation in
that 1) all elements need not be present in order to investigate how
multiple cycles act in sequence and 2) it can contain singletons:

>>> from sympy.combinatorics.permutations import Perm, Cycle

A Cycle will automatically parse a cycle given as a tuple on the rhs:

>>> Cycle(1, 2)(2, 3)
(1 3 2)

The identity cycle, Cycle(), can be used to start a product:

>>> Cycle()(1, 2)(2, 3)
(1 3 2)

The array form of a Cycle can be obtained by calling the list
method (or passing it to the list function) and all elements from
0 will be shown:

>>> a = Cycle(1, 2)
>>> a.list()
[0, 2, 1]
>>> list(a)
[0, 2, 1]

If a larger (or smaller) range is desired use the list method and
provide the desired size -- but the Cycle cannot be truncated to
a size smaller than the largest element that is out of place:

>>> b = Cycle(2, 4)(1, 2)(3, 1, 4)(1, 3)
>>> b.list()
[0, 2, 1, 3, 4]
>>> b.list(b.size + 1)
[0, 2, 1, 3, 4, 5]
>>> b.list(-1)
[0, 2, 1]

Singletons are not shown when printing with one exception: the largest
element is always shown -- as a singleton if necessary:

>>> Cycle(1, 4, 10)(4, 5)
(1 5 4 10)
>>> Cycle(1, 2)(4)(5)(10)
(1 2)(10)

The array form can be used to instantiate a Permutation so other
properties of the permutation can be investigated:

>>> Perm(Cycle(1, 2)(3, 4).list()).transpositions()
[(1, 2), (3, 4)]

Notes
=====

The underlying structure of the Cycle is a dictionary and although
the __iter__ method has been redefined to give the array form of the
cycle, the underlying dictionary items are still available with the
such methods as items():

>>> list(Cycle(1, 2).items())
[(1, 2), (2, 1)]

See Also
========

Permutation
c                     [        U5      $ )z)Enter arg into dictionary and return arg.r   )selfargs     r   __missing__Cycle.__missing__@  s    c{r>   c              #   @   #    U R                  5        S h  vN   g  N7frI   )rE   rT   s    r   __iter__Cycle.__iter__D  s     99;s   c           	          [        U6 n[        [        U R                  5       5      U R                  5        Vs/ s H	  o2X      PM     sn5       H	  u  p4XBU'   M     U$ s  snf )a  Return product of cycles processed from R to L.

Examples
========

>>> from sympy.combinatorics import Cycle
>>> Cycle(1, 2)(2, 3)
(1 3 2)

An instance of a Cycle will automatically parse list-like
objects and Permutations that are on the right. It is more
flexible than the Permutation in that all elements need not
be present:

>>> a = Cycle(1, 2)
>>> a(2, 3)
(1 3 2)
>>> a(2, 3)(4, 5)
(1 3 2)(4 5)

)rQ   ziprE   keys)rT   otherrvkvs        r   __call__Cycle.__call__G  sW    , E]TYY[)+MAtwK+MNDAqE O	 ,Ns   A
Nc                 (   U (       d  Uc  [        S5      eUbG  [        U R                  5        Vs/ s H  o U   U:w  d  M  UPM     snS/-   5      n[        XS-   5      nOU R                  n[	        U5       Vs/ s H  o U   PM	     sn$ s  snf s  snf )aO  Return the cycles as an explicit list starting from 0 up
to the greater of the largest value in the cycles and size.

Truncation of trailing unmoved items will occur when size
is less than the maximum element in the cycle; if this is
desired, setting ``size=-1`` will guarantee such trimming.

Examples
========

>>> from sympy.combinatorics import Cycle
>>> p = Cycle(2, 3)(4, 5)
>>> p.list()
[0, 1, 3, 2, 5, 4]
>>> p.list(10)
[0, 1, 3, 2, 5, 4, 6, 7, 8, 9]

Passing a length too small will trim trailing, unchanged elements
in the permutation:

>>> Cycle(2, 4)(1, 2, 4).list(-1)
[0, 2, 1]
must give size for empty Cycler   r(   )r+   maxr^   sizer8   )rT   rh   r   bigs       r   rE   
Cycle.listb  s    0 =>>$))+>+QaAq+>!DECt1W%D99D!&t-AQ--	 ? .s   B
 B
9Bc                    ^ U (       d  g[        U 5      R                  nSR                  S U 5       5      nU R                  S-
  m[	        U4S jU 5       5      (       d  UST-  -  nSU-  $ )zWe want it to print as a Cycle, not as a dict.

Examples
========

>>> from sympy.combinatorics import Cycle
>>> Cycle(1, 2)
(1 2)
>>> print(_)
(1 2)
>>> list(Cycle(1, 2).items())
[(1, 2), (2, 1)]
zCycle() c              3   J   #    U  H  n[        [        U5      5      v   M     g 7frI   strtuplerK   r;   s     r   rL   !Cycle.__repr__.<locals>.<genexpr>       26aCaMM6   !#r(   c              3   >   >#    U  H  o  H	  o"T:H  v   M     M     g 7frI   r   rK   r;   r   ri   s      r   rL   rr          7VQ8Q8V   (%s)zCycle%s)Permutationcyclic_formjoinrh   rN   rT   cyclessri   s      @r   __repr__Cycle.__repr__  se     T"..GG2622ii!m7V777#A1}r>   c                    ^ U (       d  g[        U 5      R                  nSR                  S U 5       5      nU R                  S-
  m[	        U4S jU 5       5      (       d  UST-  -  nUR                  SS5      nU$ )zWe want it to be printed in a Cycle notation with no
comma in-between.

Examples
========

>>> from sympy.combinatorics import Cycle
>>> Cycle(1, 2)
(1 2)
>>> Cycle(1, 2, 4)(5, 6)
(1 2 4)(5 6)
z()rl   c              3   J   #    U  H  n[        [        U5      5      v   M     g 7frI   rn   rq   s     r   rL    Cycle.__str__.<locals>.<genexpr>  rs   rt   r(   c              3   >   >#    U  H  o  H	  o"T:H  v   M     M     g 7frI   r   rv   s      r   rL   r     rw   rx   ry   ,)rz   r{   r|   rh   rN   replacer}   s      @r   __str__Cycle.__str__  sp     T"..GG2622ii!m7V777#AIIc2r>   c                 6   U(       d  g[        U5      S:X  a|  [        US   [        5      (       a+  US   R                   H  nU R	                  U " U6 5        M     g[        US   [
        5      (       a!  US   R                  5        H	  u  p4X@U'   M     gU Vs/ s H  n[        U5      PM     nn[        S U 5       5      (       a  [        S5      e[        U5      (       a  [        S5      e[        [        U5      * S5       H  nXS-      XU   '   M     gs  snf )zLoad up a Cycle instance with the values for the cycle.

Examples
========

>>> from sympy.combinatorics import Cycle
>>> Cycle(1, 2, 6)
(1 2 6)
Nr(   r   c              3   *   #    U  H	  oS :  v   M     g7f)r   Nr   )rK   r   s     r   rL   !Cycle.__init__.<locals>.<genexpr>  s     #d1uds   z-negative integers are not allowed in a cycle.z'All elements must be unique in a cycle.)r*   
isinstancerz   r{   updaterQ   itemsr   rN   r+   r   r8   )rT   argsr;   ra   rb   r   r   s          r   __init__Cycle.__init__  s     t9>$q';//a,,AKKa) -DGU++ GMMODAG ,#'(4aq	4(#d###LMMD>>FGGD	z1%A QKDaM & )s   Dc                 J    U (       d  g[        U R                  5       5      S-   $ Nr   r(   )rg   r^   rY   s    r   rh   
Cycle.size  s    499;!##r>   c                     [        U 5      $ rI   )rQ   rY   s    r   copy
Cycle.copy      T{r>   r   rI   )__name__
__module____qualname____firstlineno____doc__rV   rZ   rc   rE   r   r   r   propertyrh   r   __static_attributes__r   r>   r   rQ   rQ      sF    JV6.B..(< $ $
r>   rQ   c                     ^  \ rS rSrSrSrSrSrSrSr	Sr
SS.S jr\U 4S j5       rS rS	 rS
 r\S 5       rSNS jr\S 5       r\S 5       r\S 5       rS rS rS r\S 5       r\S 5       rS rS rS rS r S r!S r"S r#S r$\SNS j5       r%S r&S r'S  r(S! r)S" r*S# r+S$ r,\S% 5       r-SNS& jr.S' r/S( r0\S) 5       r1S* r2\S+ 5       r3\S, 5       r4\S- 5       r5\S. 5       r6\S/ 5       r7\S0 5       r8S1 r9S2 r:S3\;4S4 jr<S3\;4S5 jr=S6 r>S7 r?S8 r@S9 rAS: rB\S; 5       rC\S< 5       rDS= rES> rFS? rGS@ rH\SA 5       rISB rJSC rKSD rLSE rMSF rNSG rO\SOSH j5       rP\SI 5       rQ\SJ 5       rR\SK 5       rSSL rTSrUSMrVU =rW$ )Prz   i  a1  
A permutation, alternatively known as an 'arrangement number' or 'ordering'
is an arrangement of the elements of an ordered list into a one-to-one
mapping with itself. The permutation of a given arrangement is given by
indicating the positions of the elements after re-arrangement [2]_. For
example, if one started with elements ``[x, y, a, b]`` (in that order) and
they were reordered as ``[x, y, b, a]`` then the permutation would be
``[0, 1, 3, 2]``. Notice that (in SymPy) the first element is always referred
to as 0 and the permutation uses the indices of the elements in the
original ordering, not the elements ``(a, b, ...)`` themselves.

>>> from sympy.combinatorics import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)

Permutations Notation
=====================

Permutations are commonly represented in disjoint cycle or array forms.

Array Notation and 2-line Form
------------------------------------

In the 2-line form, the elements and their final positions are shown
as a matrix with 2 rows:

[0    1    2     ... n-1]
[p(0) p(1) p(2)  ... p(n-1)]

Since the first line is always ``range(n)``, where n is the size of p,
it is sufficient to represent the permutation by the second line,
referred to as the "array form" of the permutation. This is entered
in brackets as the argument to the Permutation class:

>>> p = Permutation([0, 2, 1]); p
Permutation([0, 2, 1])

Given i in range(p.size), the permutation maps i to i^p

>>> [i^p for i in range(p.size)]
[0, 2, 1]

The composite of two permutations p*q means first apply p, then q, so
i^(p*q) = (i^p)^q which is i^p^q according to Python precedence rules:

>>> q = Permutation([2, 1, 0])
>>> [i^p^q for i in range(3)]
[2, 0, 1]
>>> [i^(p*q) for i in range(3)]
[2, 0, 1]

One can use also the notation p(i) = i^p, but then the composition
rule is (p*q)(i) = q(p(i)), not p(q(i)):

>>> [(p*q)(i) for i in range(p.size)]
[2, 0, 1]
>>> [q(p(i)) for i in range(p.size)]
[2, 0, 1]
>>> [p(q(i)) for i in range(p.size)]
[1, 2, 0]

Disjoint Cycle Notation
-----------------------

In disjoint cycle notation, only the elements that have shifted are
indicated.

For example, [1, 3, 2, 0] can be represented as (0, 1, 3)(2).
This can be understood from the 2 line format of the given permutation.
In the 2-line form,
[0    1    2   3]
[1    3    2   0]

The element in the 0th position is 1, so 0 -> 1. The element in the 1st
position is three, so 1 -> 3. And the element in the third position is again
0, so 3 -> 0. Thus, 0 -> 1 -> 3 -> 0, and 2 -> 2. Thus, this can be represented
as 2 cycles: (0, 1, 3)(2).
In common notation, singular cycles are not explicitly written as they can be
inferred implicitly.

Only the relative ordering of elements in a cycle matter:

>>> Permutation(1,2,3) == Permutation(2,3,1) == Permutation(3,1,2)
True

The disjoint cycle notation is convenient when representing
permutations that have several cycles in them:

>>> Permutation(1, 2)(3, 5) == Permutation([[1, 2], [3, 5]])
True

It also provides some economy in entry when computing products of
permutations that are written in disjoint cycle notation:

>>> Permutation(1, 2)(1, 3)(2, 3)
Permutation([0, 3, 2, 1])
>>> _ == Permutation([[1, 2]])*Permutation([[1, 3]])*Permutation([[2, 3]])
True

    Caution: when the cycles have common elements between them then the order
    in which the permutations are applied matters. This module applies
    the permutations from *left to right*.

    >>> Permutation(1, 2)(2, 3) == Permutation([(1, 2), (2, 3)])
    True
    >>> Permutation(1, 2)(2, 3).list()
    [0, 3, 1, 2]

    In the above case, (1,2) is computed before (2,3).
    As 0 -> 0, 0 -> 0, element in position 0 is 0.
    As 1 -> 2, 2 -> 3, element in position 1 is 3.
    As 2 -> 1, 1 -> 1, element in position 2 is 1.
    As 3 -> 3, 3 -> 2, element in position 3 is 2.

    If the first and second elements had been
    swapped first, followed by the swapping of the second
    and third, the result would have been [0, 2, 3, 1].
    If, you want to apply the cycles in the conventional
    right to left order, call the function with arguments in reverse order
    as demonstrated below:

    >>> Permutation([(1, 2), (2, 3)][::-1]).list()
    [0, 2, 3, 1]

Entering a singleton in a permutation is a way to indicate the size of the
permutation. The ``size`` keyword can also be used.

Array-form entry:

>>> Permutation([[1, 2], [9]])
Permutation([0, 2, 1], size=10)
>>> Permutation([[1, 2]], size=10)
Permutation([0, 2, 1], size=10)

Cyclic-form entry:

>>> Permutation(1, 2, size=10)
Permutation([0, 2, 1], size=10)
>>> Permutation(9)(1, 2)
Permutation([0, 2, 1], size=10)

Caution: no singleton containing an element larger than the largest
in any previous cycle can be entered. This is an important difference
in how Permutation and Cycle handle the ``__call__`` syntax. A singleton
argument at the start of a Permutation performs instantiation of the
Permutation and is permitted:

>>> Permutation(5)
Permutation([], size=6)

A singleton entered after instantiation is a call to the permutation
-- a function call -- and if the argument is out of range it will
trigger an error. For this reason, it is better to start the cycle
with the singleton:

The following fails because there is no element 3:

>>> Permutation(1, 2)(3)
Traceback (most recent call last):
...
IndexError: list index out of range

This is ok: only the call to an out of range singleton is prohibited;
otherwise the permutation autosizes:

>>> Permutation(3)(1, 2)
Permutation([0, 2, 1, 3])
>>> Permutation(1, 2)(3, 4) == Permutation(3, 4)(1, 2)
True


Equality testing
----------------

The array forms must be the same in order for permutations to be equal:

>>> Permutation([1, 0, 2, 3]) == Permutation([1, 0])
False


Identity Permutation
--------------------

The identity permutation is a permutation in which no element is out of
place. It can be entered in a variety of ways. All the following create
an identity permutation of size 4:

>>> I = Permutation([0, 1, 2, 3])
>>> all(p == I for p in [
... Permutation(3),
... Permutation(range(4)),
... Permutation([], size=4),
... Permutation(size=4)])
True

Watch out for entering the range *inside* a set of brackets (which is
cycle notation):

>>> I == Permutation([range(4)])
False


Permutation Printing
====================

There are a few things to note about how Permutations are printed.

.. deprecated:: 1.6

   Configuring Permutation printing by setting
   ``Permutation.print_cyclic`` is deprecated. Users should use the
   ``perm_cyclic`` flag to the printers, as described below.

1) If you prefer one form (array or cycle) over another, you can set
``init_printing`` with the ``perm_cyclic`` flag.

>>> from sympy import init_printing
>>> p = Permutation(1, 2)(4, 5)(3, 4)
>>> p
Permutation([0, 2, 1, 4, 5, 3])

>>> init_printing(perm_cyclic=True, pretty_print=False)
>>> p
(1 2)(3 4 5)

2) Regardless of the setting, a list of elements in the array for cyclic
form can be obtained and either of those can be copied and supplied as
the argument to Permutation:

>>> p.array_form
[0, 2, 1, 4, 5, 3]
>>> p.cyclic_form
[[1, 2], [3, 4, 5]]
>>> Permutation(_) == p
True

3) Printing is economical in that as little as possible is printed while
retaining all information about the size of the permutation:

>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> Permutation([1, 0, 2, 3])
Permutation([1, 0, 2, 3])
>>> Permutation([1, 0, 2, 3], size=20)
Permutation([1, 0], size=20)
>>> Permutation([1, 0, 2, 4, 3, 5, 6], size=20)
Permutation([1, 0, 2, 4, 3], size=20)

>>> p = Permutation([1, 0, 2, 3])
>>> init_printing(perm_cyclic=True, pretty_print=False)
>>> p
(3)(0 1)
>>> init_printing(perm_cyclic=False, pretty_print=False)

The 2 was not printed but it is still there as can be seen with the
array_form and size methods:

>>> p.array_form
[1, 0, 2, 3]
>>> p.size
4

Short introduction to other methods
===================================

The permutation can act as a bijective function, telling what element is
located at a given position

>>> q = Permutation([5, 2, 3, 4, 1, 0])
>>> q.array_form[1] # the hard way
2
>>> q(1) # the easy way
2
>>> {i: q(i) for i in range(q.size)} # showing the bijection
{0: 5, 1: 2, 2: 3, 3: 4, 4: 1, 5: 0}

The full cyclic form (including singletons) can be obtained:

>>> p.full_cyclic_form
[[0, 1], [2], [3]]

Any permutation can be factored into transpositions of pairs of elements:

>>> Permutation([[1, 2], [3, 4, 5]]).transpositions()
[(1, 2), (3, 5), (3, 4)]
>>> Permutation.rmul(*[Permutation([ti], size=6) for ti in _]).cyclic_form
[[1, 2], [3, 4, 5]]

The number of permutations on a set of n elements is given by n! and is
called the cardinality.

>>> p.size
4
>>> p.cardinality
24

A given permutation has a rank among all the possible permutations of the
same elements, but what that rank is depends on how the permutations are
enumerated. (There are a number of different methods of doing so.) The
lexicographic rank is given by the rank method and this rank is used to
increment a permutation with addition/subtraction:

>>> p.rank()
6
>>> p + 1
Permutation([1, 0, 3, 2])
>>> p.next_lex()
Permutation([1, 0, 3, 2])
>>> _.rank()
7
>>> p.unrank_lex(p.size, rank=7)
Permutation([1, 0, 3, 2])

The product of two permutations p and q is defined as their composition as
functions, (p*q)(i) = q(p(i)) [6]_.

>>> p = Permutation([1, 0, 2, 3])
>>> q = Permutation([2, 3, 1, 0])
>>> list(q*p)
[2, 3, 0, 1]
>>> list(p*q)
[3, 2, 1, 0]
>>> [q(p(i)) for i in range(p.size)]
[3, 2, 1, 0]

The permutation can be 'applied' to any list-like object, not only
Permutations:

>>> p(['zero', 'one', 'four', 'two'])
['one', 'zero', 'four', 'two']
>>> p('zo42')
['o', 'z', '4', '2']

If you have a list of arbitrary elements, the corresponding permutation
can be found with the from_sequence method:

>>> Permutation.from_sequence('SymPy')
Permutation([1, 3, 2, 0, 4])

Checking if a Permutation is contained in a Group
=================================================

Generally if you have a group of permutations G on n symbols, and
you're checking if a permutation on less than n symbols is part
of that group, the check will fail.

Here is an example for n=5 and we check if the cycle
(1,2,3) is in G:

>>> from sympy import init_printing
>>> init_printing(perm_cyclic=True, pretty_print=False)
>>> from sympy.combinatorics import Cycle, Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> G = PermutationGroup(Cycle(2, 3)(4, 5), Cycle(1, 2, 3, 4, 5))
>>> p1 = Permutation(Cycle(2, 5, 3))
>>> p2 = Permutation(Cycle(1, 2, 3))
>>> a1 = Permutation(Cycle(1, 2, 3).list(6))
>>> a2 = Permutation(Cycle(1, 2, 3)(5))
>>> a3 = Permutation(Cycle(1, 2, 3),size=6)
>>> for p in [p1,p2,a1,a2,a3]: p, G.contains(p)
((2 5 3), True)
((1 2 3), False)
((5)(1 2 3), True)
((5)(1 2 3), True)
((5)(1 2 3), True)

The check for p2 above will fail.

Checking if p1 is in G works because SymPy knows
G is a group on 5 symbols, and p1 is also on 5 symbols
(its largest element is 5).

For ``a1``, the ``.list(6)`` call will extend the permutation to 5
symbols, so the test will work as well. In the case of ``a2`` the
permutation is being extended to 5 symbols by using a singleton,
and in the case of ``a3`` it's extended through the constructor
argument ``size=6``.

There is another way to do this, which is to tell the ``contains``
method that the number of symbols the group is on does not need to
match perfectly the number of symbols for the permutation:

>>> G.contains(p2,strict=False)
True

This can be via the ``strict`` argument to the ``contains`` method,
and SymPy will try to extend the permutation on its own and then
perform the containment check.

See Also
========

Cycle

References
==========

.. [1] Skiena, S. 'Permutations.' 1.1 in Implementing Discrete Mathematics
       Combinatorics and Graph Theory with Mathematica.  Reading, MA:
       Addison-Wesley, pp. 3-16, 1990.

.. [2] Knuth, D. E. The Art of Computer Programming, Vol. 4: Combinatorial
       Algorithms, 1st ed. Reading, MA: Addison-Wesley, 2011.

.. [3] Wendy Myrvold and Frank Ruskey. 2001. Ranking and unranking
       permutations in linear time. Inf. Process. Lett. 79, 6 (September 2001),
       281-284. DOI=10.1016/S0020-0190(01)00141-7

.. [4] D. L. Kreher, D. R. Stinson 'Combinatorial Algorithms'
       CRC Press, 1999

.. [5] Graham, R. L.; Knuth, D. E.; and Patashnik, O.
       Concrete Mathematics: A Foundation for Computer Science, 2nd ed.
       Reading, MA: Addison-Wesley, 1994.

.. [6] https://en.wikipedia.org/w/index.php?oldid=499948155#Product_and_inverse

.. [7] https://en.wikipedia.org/wiki/Lehmer_code

TNrh   c          
      Z   Ub  [        U5      nSnU(       d,  U R                  [        [        U=(       d    S5      5      5      $ [	        U5      S:  a&  U R                  [        U6 R                  U5      5      $ [	        U5      S:X  a  US   n[        XP5      (       a%  Ub  XR                  :X  a  U$ U " UR                  US9$ [        U[
        5      (       a   U R                  UR                  U5      5      $ [        U5      (       d@  Ub  US-   U:  a  [        SU-  5      eU R                  [        [        US-   5      5      5      $ [        S U 5       5      (       a  SnOSnU(       d  [        S5      e[        US   5      nU=(       a    [        US   5      nU(       a.  U VVs/ s H  ow Vs/ s H  n[        U5      PM     snPM      nnnOU Vs/ s H  n[        U5      PM     nn[        U5      n	[        U	5      (       a  U(       d  [        S	5      e[        U	5      n	U(       de  U	[        [        [	        U	5      5      5      :w  a  [        S
[        U	5      -  5      eUb*  U	(       a#  [        U	5      S-   U:  a  [        SUS-
  -  5      eU(       a)  [        5       nU H  n
U" U
6 nM
     UR                  5       nO[        U5      nU(       a<  U[	        U5      :  a-  UR!                  [        [        [	        U5      U5      5      5        U R                  U5      $ s  snf s  snnf s  snf )ap  
Constructor for the Permutation object from a list or a
list of lists in which all elements of the permutation may
appear only once.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)

Permutations entered in array-form are left unaltered:

>>> Permutation([0, 2, 1])
Permutation([0, 2, 1])

Permutations entered in cyclic form are converted to array form;
singletons need not be entered, but can be entered to indicate the
largest element:

>>> Permutation([[4, 5, 6], [0, 1]])
Permutation([1, 0, 2, 3, 5, 6, 4])
>>> Permutation([[4, 5, 6], [0, 1], [19]])
Permutation([1, 0, 2, 3, 5, 6, 4], size=20)

All manipulation of permutations assumes that the smallest element
is 0 (in keeping with 0-based indexing in Python) so if the 0 is
missing when entering a permutation in array form, an error will be
raised:

>>> Permutation([2, 1])
Traceback (most recent call last):
...
ValueError: Integers 0 through 2 must be present.

If a permutation is entered in cyclic form, it can be entered without
singletons and the ``size`` specified so those values can be filled
in, otherwise the array form will only extend to the maximum value
in the cycles:

>>> Permutation([[1, 4], [3, 5, 2]], size=10)
Permutation([0, 4, 3, 5, 1, 2], size=10)
>>> _.array_form
[0, 4, 3, 5, 1, 2, 6, 7, 8, 9]
Tr   r(   r   z size is too small when max is %sc              3   8   #    U  H  n[        U5      v   M     g 7frI   )r   )rK   rB   s     r   rL   &Permutation.__new__.<locals>.<genexpr>  s     7Qr;r??Qs   FzSPermutation argument must be a list of ints, a list of lists, Permutation or Cycle.zthere were repeated elements.z&Integers 0 through %s must be present.z max element should not exceed %s)int_af_newrE   r8   r*   rQ   r   rh   
array_formr   r+   r   r   r   setrg   extend)clsrh   r   kwargsokr   is_cycler;   r   tempciaforms               r   __new__Permutation.__new__  s   ^ t9D ;;tE$)!$4566Y];;ud|00677t9>QA!!!<466>H1<<d33!U##{{166$<00q>>#A$%G!%KLL{{4a!e#5667Q777B F G G
 DG}0KQ0156AQ'QSVQ'D6D$()DqCFDD) t}D>>(<==4ys5T+,, !ID	"  DSY]T-A !Ctax!PQQ ArF FFHEJED3u:% LLeCJ567{{5!!I (6)s   &	L"/LL"L(L"c                 R   > [         TU ]  U 5      nXl        [        U5      Ul        U$ )a9  A method to produce a Permutation object from a list;
the list is bound to the _array_form attribute, so it must
not be modified; this method is meant for internal use only;
the list ``a`` is supposed to be generated as a temporary value
in a method, so p = Perm._af_new(a) is the only object
to hold a reference to ``a``::

Examples
========

>>> from sympy.combinatorics.permutations import Perm
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> a = [2, 1, 3, 0]
>>> p = Perm._af_new(a)
>>> p
Permutation([2, 1, 3, 0])

)superr   _array_formr*   _size)r   permp	__class__s      r   r   Permutation._af_new  s(    * GOC d)r>   c                 8    U R                  U R                  5      $ rI   )r   r   rY   s    r   r   Permutation.copy  s    ~~doo..r>   c                     U R                   4$ rI   r   rY   s    r   __getnewargs__Permutation.__getnewargs__!  s    !!r>   c                 ,    [        U R                  5      $ rI   )rp   r   rY   s    r   _hashable_contentPermutation._hashable_content$  s     T__%%r>   c                      U R                   SS $ )aa  
Return a copy of the attribute _array_form
Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([[2, 0], [3, 1]])
>>> p.array_form
[2, 3, 0, 1]
>>> Permutation([[2, 0, 3, 1]]).array_form
[3, 2, 0, 1]
>>> Permutation([2, 0, 3, 1]).array_form
[2, 0, 3, 1]
>>> Permutation([[1, 2], [4, 5]]).array_form
[0, 2, 1, 3, 5, 4]
N)r   rY   s    r   r   Permutation.array_form)  s    $ ""r>   c                 L   U (       d  Uc  [        S5      eU R                  nUb  XR                  :  a0  UR                  [	        [        U R                  U5      5      5        U$ U R                  S-
  nU(       a*  US   U:w  a   U$ UR                  5         US-  nU(       a  M*  U$ )a-  Return the permutation as an explicit list, possibly
trimming unmoved elements if size is less than the maximum
element in the permutation; if this is desired, setting
``size=-1`` will guarantee such trimming.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation(2, 3)(4, 5)
>>> p.list()
[0, 1, 3, 2, 5, 4]
>>> p.list(10)
[0, 1, 3, 2, 5, 4, 6, 7, 8, 9]

Passing a length too small will trim trailing, unchanged elements
in the permutation:

>>> Permutation(2, 4)(1, 2, 4).list(-1)
[0, 2, 1]
>>> Permutation(3).list(-1)
[]
rf   r(   )r+   r   rh   r   rE   r8   pop)rT   rh   r`   r   s       r   rE   Permutation.list=  s    0 =>>__ii		$uTYY567 	 IIM"v{ 	 FFHFA	 b
 	r>   c                 *   U R                   b  [        U R                   5      $ U R                  nS/[        U5      -  n/ n[	        [        U5      5       H  nX$   (       d  M  / nUR                  U5        SX$'   UnX!U      (       a'  X   nUR                  U5        SX&'   X!U      (       a  M'  [        U5      S:  d  Mk  UR                  U5        U[        [        U5      5      :X  a  M   e   UR                  5         UR                  5       U l         U$ )a[  
This is used to convert to the cyclic notation
from the canonical notation. Singletons are omitted.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([0, 3, 1, 2])
>>> p.cyclic_form
[[1, 3, 2]]
>>> Permutation([1, 0, 2, 4, 3, 5]).cyclic_form
[[0, 1], [3, 4]]

See Also
========

array_form, full_cyclic_form
TFr(   )	_cyclic_formrE   r   r*   r8   appendr   sortr   )rT   r   	uncheckedr{   r   cycler<   s          r   r{   Permutation.cyclic_forme  s    * ())**__
FS_,	s:'A||Q$	1."ALLO#(IL  1.. u:>&&u- D$7777 ( 	',,.r>   c                     [        [        U R                  5      5      [        [        U R                  5      5      -
  nU R                  U Vs/ s H  o"/PM     sn-   nUR                  5         U$ s  snf )zReturn permutation in cyclic form including singletons.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> Permutation([0, 2, 1]).full_cyclic_form
[[0], [1, 2]]
)r   r8   rh   r   r{   r   )rT   needr   r`   s       r   full_cyclic_formPermutation.full_cyclic_form  s^     5#$s743C3C+D'EEd 3dd 33
		 !4s   A0c                     U R                   $ )z
Returns the number of elements in the permutation.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> Permutation([[3, 2], [0, 1]]).size
4

See Also
========

cardinality, length, order, rank
)r   rY   s    r   rh   Permutation.size  s    " zzr>   c                 t    U R                   n[        U5       VVs/ s H  u  p#X2:w  d  M  UPM     snn$ s  snnf )zReturn the elements in permutation, P, for which P[i] != i.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([[3, 2], [0, 1], [4]])
>>> p.array_form
[1, 0, 3, 2, 4]
>>> p.support()
[0, 1, 2, 3]
)r   r@   )rT   r   r   es       r   supportPermutation.support  s/     OO'l5ldaafl555s   44c                     U R                  5       U-   U R                  -  nU R                  U R                  U5      nX#l        U$ )ad  Return permutation that is other higher in rank than self.

The rank is the lexicographical rank, with the identity permutation
having rank of 0.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> I = Permutation([0, 1, 2, 3])
>>> a = Permutation([2, 1, 3, 0])
>>> I + a.rank() == a
True

See Also
========

__sub__, inversion_vector

)rankcardinality
unrank_lexrh   _rank)rT   r_   r   r`   s       r   __add__Permutation.__add__  s=    * 		e#t'7'77__TYY-	r>   c                 &    U R                  U* 5      $ )zZReturn the permutation that is other lower in rank than self.

See Also
========

__add__
)r   )rT   r_   s     r   __sub__Permutation.__sub__  s     ||UF##r>   c                  V    U S   n[        S[        U 5      5       H
  nX   U-  nM     U$ )a/  
Return product of Permutations [a, b, c, ...] as the Permutation whose
ith value is a(b(c(i))).

a, b, c, ... can be Permutation objects or tuples.

Examples
========

>>> from sympy.combinatorics import Permutation

>>> a, b = [1, 0, 2], [0, 2, 1]
>>> a = Permutation(a); b = Permutation(b)
>>> list(Permutation.rmul(a, b))
[1, 2, 0]
>>> [a(b(i)) for i in range(3)]
[1, 2, 0]

This handles the operands in reverse order compared to the ``*`` operator:

>>> a = Permutation(a); b = Permutation(b)
>>> list(a*b)
[2, 0, 1]
>>> [b(a(i)) for i in range(3)]
[2, 0, 1]

Notes
=====

All items in the sequence will be parsed by Permutation as
necessary as long as the first item is a Permutation:

>>> Permutation.rmul(a, [0, 2, 1]) == Permutation.rmul(a, b)
True

The reverse order of arguments will raise a TypeError.

r   r(   )r8   r*   )r   r`   r   s      r   rmulPermutation.rmul  s3    P !Wq#d)$AB %	r>   c                 t    U Vs/ s H  o"R                   PM     nnU R                  [        U6 5      nU$ s  snf )zW
same as rmul, but the elements of args are Permutation objects
which have _array_form
)r   r   r,   )r   r   xr   r`   s        r   rmul_with_afPermutation.rmul_with_af  s6     %))Dq]]D)[[A'	 *s   5c                 x    [        U R                  5      nUR                  nU R                  [        X#5      5      $ )z.
other*~self, self and other have _array_form
)rC   r   r   r    rT   r_   r   r   s       r   mul_invPermutation.mul_inv  s2     t''(||HQN++r>   c                 .    [        U 5      nU" U5      U -  $ )z6This is needed to coerce other to Permutation in rmul.)type)rT   r_   r   s      r   __rmul__Permutation.__rmul__&  s    4j5z$r>   c           
      d   SSK JnJn  [        X5      (       a  U" XSS9$ U R                  nUR                  nU(       d  UnOZUR                  [        [        [        U5      [        U5      5      5      5        U Vs/ s H  ouU   PM	     snU[        U5      S -   nU R                  U5      $ s  snf )ab  
Return the product a*b as a Permutation; the ith value is b(a(i)).

Examples
========

>>> from sympy.combinatorics.permutations import _af_rmul, Permutation

>>> a, b = [1, 0, 2], [0, 2, 1]
>>> a = Permutation(a); b = Permutation(b)
>>> list(a*b)
[2, 0, 1]
>>> [b(a(i)) for i in range(3)]
[2, 0, 1]

This handles operands in reverse order compared to _af_rmul and rmul:

>>> al = list(a); bl = list(b)
>>> _af_rmul(al, bl)
[1, 2, 0]
>>> [al[bl[i]] for i in range(3)]
[1, 2, 0]

It is acceptable for the arrays to have different lengths; the shorter
one will be padded to match the longer one:

>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> b*Permutation([1, 0])
Permutation([1, 2, 0])
>>> Permutation([1, 0])*b
Permutation([2, 0, 1])

It is also acceptable to allow coercion to handle conversion of a
single list to the left of a Permutation:

>>> [0, 1]*a # no change: 2-element identity
Permutation([1, 0, 2])
>>> [[0, 1]]*a # exchange first two elements
Permutation([0, 1, 2])

You cannot use more than 1 cycle notation in a product of cycles
since coercion can only handle one argument to the left. To handle
multiple cycles it is convenient to use Cycle instead of Permutation:

>>> [[1, 2]]*[[2, 3]]*Permutation([]) # doctest: +SKIP
>>> from sympy.combinatorics.permutations import Cycle
>>> Cycle(1, 2)(2, 3)
(1 3 2)

r   )PermutationGroupCoset-)dirN)
sympy.combinatorics.perm_groupsr   r   r   r   r   rE   r8   r*   r   )rT   r_   r   r   r   r   r   r   s           r   __mul__Permutation.__mul__+  s    h 	Le..#..OODHHT%AA/01"#$!QaD!$qQz1D||D!! %s   <B-c                 H    U R                   nUR                   n[        X#5      $ )a  
Checks if the elements are commuting.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> a = Permutation([1, 4, 3, 0, 2, 5])
>>> b = Permutation([0, 1, 2, 3, 4, 5])
>>> a.commutes_with(b)
True
>>> b = Permutation([2, 3, 5, 4, 1, 0])
>>> a.commutes_with(b)
False
)r   rO   r   s       r   commutes_withPermutation.commutes_withl  s#      OO &&r>   c                     [        U[        5      (       a  [        S5      e[        U5      nU R	                  [        U R                  U5      5      $ )a$  
Routine for finding powers of a permutation.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> p = Permutation([2, 0, 3, 1])
>>> p.order()
4
>>> p**4
Permutation([0, 1, 2, 3])
z1p**p is not defined; do you mean p^p (conjugate)?)r   rz   NotImplementedErrorr   r   rF   r   )rT   r:   s     r   __pow__Permutation.__pow__  sF      a%%%CE EF||GDOOQ788r>   c                 N    [        U5      (       a  U " U5      $ [        SU-  5      e)zReturn self(i) when ``i`` is an int.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation(1, 2, 9)
>>> 2^p == p(2) == 9
True
z(i^p = p(i) when i is an integer, not %s.)r	   r  )rT   r   s     r   __rxor__Permutation.__rxor__  s-     a==7N%:Q>@ @r>   c                    U R                   UR                   :w  a  [        S5      eS/U R                   -  nUR                  nU R                  n[        U R                   5       H  nXU      X!U   '   M     U R	                  U5      $ )a  Return the conjugate permutation ``~h*self*h` `.

Explanation
===========

If ``a`` and ``b`` are conjugates, ``a = h*b*~h`` and
``b = ~h*a*h`` and both have the same cycle structure.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation(1, 2, 9)
>>> q = Permutation(6, 9, 8)
>>> p*q != q*p
True

Calculate and check properties of the conjugate:

>>> c = p^q
>>> c == ~q*p*q and p == q*c*~q
True

The expression q^p^r is equivalent to q^(p*r):

>>> r = Permutation(9)(4, 6, 8)
>>> q^p^r == q^(p*r)
True

If the term to the left of the conjugate operator, i, is an integer
then this is interpreted as selecting the ith element from the
permutation to the right:

>>> all(i^p == p(i) for i in range(p.size))
True

Note that the * operator as higher precedence than the ^ operator:

>>> q^r*p^r == q^(r*p)^r == Permutation(9)(1, 6, 4)
True

Notes
=====

In Python the precedence rule is p^q^r = (p^q)^r which differs
in general from p^(q^r)

>>> q^p^r
(9)(1 4 8)
>>> q^(p^r)
(9)(1 8 6)

For a given r and p, both of the following are conjugates of p:
~r*p*r and r*p*~r. But these are not necessarily the same:

>>> ~r*p*r == r*p*~r
True

>>> p = Permutation(1, 2, 9)(5, 6)
>>> ~r*p*r == r*p*~r
False

The conjugate ~r*p*r was chosen so that ``p^q^r`` would be equivalent
to ``p^(q*r)`` rather than ``p^(r*q)``. To obtain r*p*~r, pass ~r to
this method:

>>> p^~r == r*p*~r
True
'The permutations must be of equal size.N)rh   r+   r   r8   r   )rT   hr   r   r   s        r   __xor__Permutation.__xor__  sw    N 99FGGF499MMtyy!A!gAdG "||Ar>   c                    ^ U R                   n/ nU H`  n[        U5      nUS:X  a  UR                  [        U5      5        M0  US:  d  M8  US   mUR	                  U4S jX4S-
  SS2    5       5        Mb     U$ )a  
Return the permutation decomposed into a list of transpositions.

Explanation
===========

It is always possible to express a permutation as the product of
transpositions, see [1]

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([[1, 2, 3], [0, 4, 5, 6, 7]])
>>> t = p.transpositions()
>>> t
[(0, 7), (0, 6), (0, 5), (0, 4), (1, 3), (1, 2)]
>>> print(''.join(str(c) for c in t))
(0, 7)(0, 6)(0, 5)(0, 4)(1, 3)(1, 2)
>>> Permutation.rmul(*[Permutation([ti], size=p.size) for ti in t]) == p
True

References
==========

.. [1] https://en.wikipedia.org/wiki/Transposition_%28mathematics%29#Properties

r)   r   c              3   ,   >#    U  H	  nTU4v   M     g 7frI   r   )rK   yfirsts     r   rL   -Permutation.transpositions.<locals>.<genexpr>  s     >~!E1:~s   r(   r   )r{   r*   r   rp   r   )rT   r   resr   nxr  s        @r   transpositionsPermutation.transpositions  st    : AQBQw

58$a!

>qa"~>>  
r>   c                   ^ [        [        U[        [        [        U5      5      5      5      5      nT(       a  UR	                  U4S jS9  OUR	                  5         [        U Vs/ s H  oS   PM	     sn5      ) $ s  snf )ay  Return the permutation needed to obtain ``i`` from the sorted
elements of ``i``. If custom sorting is desired, a key can be given.

Examples
========

>>> from sympy.combinatorics import Permutation

>>> Permutation.from_sequence('SymPy')
(4)(0 1 3)
>>> _(sorted("SymPy"))
['S', 'y', 'm', 'P', 'y']
>>> Permutation.from_sequence('SymPy', key=lambda x: x.lower())
(4)(0 2)(1 3)
c                    > T" U S   5      $ )Nr   r   )r   keys    r   <lambda>+Permutation.from_sequence.<locals>.<lambda>2  s    #ad)r>   )r  r(   )rE   r]   r8   r*   r   rz   )rT   r   r  ics     ` r   from_sequencePermutation.from_sequence  s`    " #aeCFm,-.GG+G,GGI2.2aqT2.///.s   &A<c                 J    U R                  [        U R                  5      5      $ )a  
Return the inverse of the permutation.

A permutation multiplied by its inverse is the identity permutation.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> p = Permutation([[2, 0], [3, 1]])
>>> ~p
Permutation([2, 3, 0, 1])
>>> _ == p**-1
True
>>> p*~p == ~p*p == Permutation([0, 1, 2, 3])
True
)r   rC   r   rY   s    r   
__invert__Permutation.__invert__7  s    ( ||Jt'7'7899r>   c              #   8   #    U R                    Sh  vN   g N7f)zYield elements from array form.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> list(Permutation(range(3)))
[0, 1, 2]
Nr   rY   s    r   rZ   Permutation.__iter__M  s      ??""s   c                     [        U 5      $ rI   r   rY   s    r   r   Permutation.__repr__Y  r   r>   c                    [        U5      S:X  a  US   n[        U[        5      (       dV  [        U5      nUS:  d  XR                  :  a'  [        SR                  XR                  S-
  5      5      eU R                  U   $ [        U5      U R                  :w  a$  [        SR                  XR                  5      5      eU R                   Vs/ s H  o!U   PM	     sn$ U [        [        U6 U R                  S9-  $ s  snf )a  
Allows applying a permutation instance as a bijective function.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([[2, 0], [3, 1]])
>>> p.array_form
[2, 3, 0, 1]
>>> [p(i) for i in range(4)]
[2, 3, 0, 1]

If an array is given then the permutation selects the items
from the array (i.e. the permutation is applied to the array):

>>> from sympy.abc import x
>>> p([x, 1, 0, x**2])
[0, x**2, x, 1]
r(   r   ({} should be an integer between 0 and {}z{} should have the length {}.r   )
r*   r   r   r   rh   	TypeErrorformatr   rz   rQ   )rT   r   r<   s      r   rc   Permutation.__call__\  s    0 q6Q;!Aa**1Iq5A		M#B99Q;/1 1 ''**1v"3::1iiHJ J"&"2"23"2QaD"233Kq			::: 4s   C9c                 ,    [        U R                  5      $ )z
Returns all the elements of a permutation

Examples
========

>>> from sympy.combinatorics import Permutation
>>> Permutation([0, 1, 2, 3, 4, 5]).atoms()
{0, 1, 2, 3, 4, 5}
>>> Permutation([[0, 1], [2, 3], [4, 5]]).atoms()
{0, 1, 2, 3, 4, 5}
)r   r   rY   s    r   atomsPermutation.atoms  s     4??##r>   c                 F   [        U5      nUR                  SL a  [        SR                  U5      5      eU R                  nUS:  S:X  d  X:  S:X  a  [        SR                  XS-
  5      5      eUR
                  (       a  [        U R                  U   5      $ [        X5      $ )aj  Apply the permutation to an expression.

Parameters
==========

i : Expr
    It should be an integer between $0$ and $n-1$ where $n$
    is the size of the permutation.

    If it is a symbol or a symbolic expression that can
    have integer values, an ``AppliedPermutation`` object
    will be returned which can represent an unevaluated
    function.

Notes
=====

Any permutation can be defined as a bijective function
$\sigma : \{ 0, 1, \dots, n-1 \} \rightarrow \{ 0, 1, \dots, n-1 \}$
where $n$ denotes the size of the permutation.

The definition may even be extended for any set with distinctive
elements, such that the permutation can even be applied for
real numbers or such, however, it is not implemented for now for
computational reasons and the integrity with the group theory
module.

This function is similar to the ``__call__`` magic, however,
``__call__`` magic already has some other applications like
permuting an array or attaching new cycles, which would
not always be mathematically consistent.

This also guarantees that the return type is a SymPy integer,
which guarantees the safety to use assumptions.
Fz{} should be an integer.r   Tr%  r(   )	r   
is_integerr  r'  rh   
is_Integerr
   r   AppliedPermutation)rT   r   r:   s      r   applyPermutation.apply  s    H QK<<5 %&@&G&G&JKKIIEd?qv$.%:AA!qSIK K <<4++A.//!$**r>   c                 f   U R                   SS n[        U5      nUS-
  nXS-      X   :  a  US-  nXS-      X   :  a  M  US:X  a  gUS-
  nX   X   :  a  US-  nX   X   :  a  M  X   X   sX'   X'   US-  nUS-
  nX4:  a  X   X   sX'   X'   US-  nUS-  nX4:  a  M  U R                  U5      $ )at  
Returns the next permutation in lexicographical order.
If self is the last permutation in lexicographical order
it returns None.
See [4] section 2.4.


Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([2, 3, 1, 0])
>>> p = Permutation([2, 3, 1, 0]); p.rank()
17
>>> p = p.next_lex(); p.rank()
18

See Also
========

rank, unrank_lex
Nr)   r(   r   )r   r*   r   )rT   r   r:   r   r<   s        r   next_lexPermutation.next_lex  s    . q!IEq5kDG#FA q5kDG#7AA'DG#Q 'DG##wDGTWFAAA%#'7DG QQ % ||D!!r>   c                    ^ U4S jm[        [        U5      5      n[        U5      nU[        U5      -  nT" XU5        U R	                  U5      $ )a  
This is a linear time unranking algorithm that does not
respect lexicographic order [3].

Examples
========

>>> from sympy.combinatorics import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> Permutation.unrank_nonlex(4, 5)
Permutation([2, 0, 3, 1])
>>> Permutation.unrank_nonlex(4, -1)
Permutation([0, 1, 2, 3])

See Also
========

next_nonlex, rank_nonlex
c                 d   > U S:  a)  X!U -     X S-
     sX S-
  '   X!U -  '   T" U S-
  X-  U5        g g r   r   )r:   rr   _unrank1s      r   r8  +Permutation.unrank_nonlex.<locals>._unrank1  sE    1u%&1uXqQx"a%!E(Qa( r>   )rE   r8   r   r   r   )rT   r:   r7  id_permr8  s       @r   unrank_nonlexPermutation.unrank_nonlex  sF    ,	)
 uQx.FQKw||G$$r>   c                    ^ U4S jmUc  U ) R                   nU(       d  gU R                   SS nT" [        U5      X!5      nU$ )a  
This is a linear time ranking algorithm that does not
enforce lexicographic order [3].


Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.rank_nonlex()
23

See Also
========

next_nonlex, unrank_nonlex
c                    > U S:X  a  gXS-
     nX S-
     nX   UsXS-
  '   X'   X#   UsX S-
  '   X#'   X0T" U S-
  X5      -  -   $ )Nr(   r   r   )r:   r   inv_permr   t_rank1s        r   rA  'Permutation.rank_nonlex.<locals>._rank1$  sh    AvUAQA#'7A DQK+3;(HUOX[At6666r>   Nr   )r   r*   )rT   r?  r   r7  rA  s       @r   rank_nonlexPermutation.rank_nonlex  sF    &	7 ))Hq!3t9d-r>   c                     U R                  5       nU[        U R                  5      S-
  :X  a  gU R                  U R                  US-   5      $ )a  
Returns the next permutation in nonlex order [3].
If self is the last permutation in this order it returns None.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> p = Permutation([2, 0, 3, 1]); p.rank_nonlex()
5
>>> p = p.next_nonlex(); p
Permutation([3, 0, 1, 2])
>>> p.rank_nonlex()
6

See Also
========

rank_nonlex, unrank_nonlex
r(   N)rC  r   rh   r;  )rT   r7  s     r   next_nonlexPermutation.next_nonlex5  sE    . TYY!##!!$))QU33r>   c                 b   U R                   b  U R                   $ SnU R                  SS nU R                  S-
  nUS-   n[        [	        U5      5      n[        US-
  5       HD  nXU   U-  -  n[        US-   U5       H  nX'   X&   :  d  M  X'==   S-  ss'   M     XS-  nUS-  nMF     Xl         U$ )a&  
Returns the lexicographic rank of the permutation.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.rank()
0
>>> p = Permutation([3, 2, 1, 0])
>>> p.rank()
23

See Also
========

next_lex, unrank_lex, cardinality, length, order, size
Nr   r(   )r   r   rh   r   r   r8   )rT   r   rhor:   rh   psizer<   r   s           r   r   Permutation.rankQ  s    ( ::!::ooa IIM1uDGtaxAF5L D1q5$'6CF?FaKF ( KEFA ! 
r>   c                 >    [        [        U R                  5      5      $ )z
Returns the number of all possible permutations.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.cardinality
24

See Also
========

length, order, rank, size
)r   r   rh   rY   s    r   r   Permutation.cardinalityv  s    $ 4		?##r>   c                 ~    U R                   b  U R                  U R                  -
  S-  $ [        U R                  5      $ )a  
Computes the parity of a permutation.

Explanation
===========

The parity of a permutation reflects the parity of the
number of inversions in the permutation, i.e., the
number of pairs of x and y such that ``x > y`` but ``p[x] < p[y]``.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.parity()
0
>>> p = Permutation([3, 2, 0, 1])
>>> p.parity()
1

See Also
========

_af_parity
r)   )r   rh   r~   r=   r   rY   s    r   parityPermutation.parity  s7    6 (II+q00$//**r>   c                 $    U R                   (       + $ )z
Checks if a permutation is even.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.is_even
True
>>> p = Permutation([3, 2, 1, 0])
>>> p.is_even
True

See Also
========

is_odd
)is_oddrY   s    r   is_evenPermutation.is_even  s    * ;;r>   c                 :    [        U R                  5       S-  5      $ )z
Checks if a permutation is odd.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.is_odd
False
>>> p = Permutation([3, 2, 0, 1])
>>> p.is_odd
True

See Also
========

is_even
r)   )boolrO  rY   s    r   rR  Permutation.is_odd  s    * DKKMA%&&r>   c                      U R                   S:H  $ )a/  
Checks to see if the permutation contains only one number and is
thus the only possible permutation of this set of numbers

Examples
========

>>> from sympy.combinatorics import Permutation
>>> Permutation([0]).is_Singleton
True
>>> Permutation([0, 1]).is_Singleton
False

See Also
========

is_Empty
r(   r   rY   s    r   is_SingletonPermutation.is_Singleton  s    ( yyA~r>   c                      U R                   S:H  $ )z
Checks to see if the permutation is a set with zero elements

Examples
========

>>> from sympy.combinatorics import Permutation
>>> Permutation([]).is_Empty
True
>>> Permutation([0]).is_Empty
False

See Also
========

is_Singleton
r   r   rY   s    r   is_EmptyPermutation.is_Empty  s    & yyA~r>   c                     U R                   $ rI   )is_IdentityrY   s    r   is_identityPermutation.is_identity  s    r>   c                    ^ U R                   mT(       + =(       d(    [        U4S j[        U R                  5       5       5      $ )as  
Returns True if the Permutation is an identity permutation.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([])
>>> p.is_Identity
True
>>> p = Permutation([[0], [1], [2]])
>>> p.is_Identity
True
>>> p = Permutation([0, 1, 2])
>>> p.is_Identity
True
>>> p = Permutation([0, 2, 1])
>>> p.is_Identity
False

See Also
========

order
c              3   2   >#    U  H  oTU   :H  v   M     g 7frI   r   )rK   r   afs     r   rL   *Permutation.is_Identity.<locals>.<genexpr>#  s     B1AA"Q%Z1As   )r   allr8   rh   )rT   rd  s    @r   r_  Permutation.is_Identity  s/    6 __vBBtyy1ABBBr>   c                     U R                   n[        [        U5      S-
  5       Vs/ s H  o!U   XS-      :  d  M  UPM     nnU$ s  snf )a  
Returns the positions of ascents in a permutation, ie, the location
where p[i] < p[i+1]

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([4, 0, 1, 3, 2])
>>> p.ascents()
[1, 2]

See Also
========

descents, inversions, min, max
r(   r   r8   r*   rT   r   r   poss       r   ascentsPermutation.ascents%  I    $ OOA
+?+QtaAhq+?
 @
   AAc                     U R                   n[        [        U5      S-
  5       Vs/ s H  o!U   XS-      :  d  M  UPM     nnU$ s  snf )a  
Returns the positions of descents in a permutation, ie, the location
where p[i] > p[i+1]

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([4, 0, 1, 3, 2])
>>> p.descents()
[0, 3]

See Also
========

ascents, inversions, min, max
r(   ri  rj  s       r   descentsPermutation.descents;  rn  ro  returnc                 `    U R                   nU(       d  g[        S [        U5       5       5      $ )z
The maximum element moved by the permutation.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([1, 0, 2, 3, 4])
>>> p.max()
1

See Also
========

min, descents, ascents, inversions
r   c              3   8   #    U  H  u  pX!:w  d  M  Uv   M     g 7frI   r   rK   r   _as      r   rL   "Permutation.max.<locals>.<genexpr>e       ;<%!2722<   	)r   rg   r@   rT   r   s     r   rg   Permutation.maxQ  (    " OO;9Q<;;;r>   c                 `    U R                   nU(       d  g[        S [        U5       5       5      $ )z
The minimum element moved by the permutation.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([0, 1, 4, 3, 2])
>>> p.min()
2

See Also
========

max, descents, ascents, inversions
r   c              3   8   #    U  H  u  pX!:w  d  M  Uv   M     g 7frI   r   rv  s      r   rL   "Permutation.min.<locals>.<genexpr>{  ry  rz  )r   minr@   r{  s     r   r  Permutation.ming  r}  r>   c                 p   SnU R                   n[        U5      nUS:  a5  [        US-
  5       H!  nX$   nX$S-   S  H  nXV:  d  M
  US-  nM     M#     U$ SnSnUSS n	USS n
Xs:  aN  SnXG-   U:  a8  XGS-  -   S-
  nX:  a  US-
  nU[        XXDU-   U5      -  nXGS-  -   nXG-   U:  a  M8  US-  nXs:  a  MN  U$ )a  
Computes the number of inversions of a permutation.

Explanation
===========

An inversion is where i > j but p[i] < p[j].

For small length of p, it iterates over all i and j
values and calculates the number of inversions.
For large length of p, it uses a variation of merge
sort to calculate the number of inversions.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([0, 1, 2, 3, 4, 5])
>>> p.inversions()
0
>>> Permutation([3, 2, 1, 0]).inversions()
6

See Also
========

descents, ascents, min, max

References
==========

.. [1] https://www.cp.eng.chula.ac.th/~prabhas//teaching/algo/algo2008/count-inv.htm

r      r(   Nr)   )r   r*   r8   _merge)rT   
inversionsr   r:   r   r   r;   ra   rightarrr   s              r   r  Permutation.inversions}  s    F 
OOFs71q5\Dq56Au"a
 # "&  AEA$CQ4D%eaiAIMEz !A&A1ue"DDJE	A eai E % r>   c           	      P   U R                   nUR                   n[        U5      n[        U5      U:w  a  [        S5      eS/U-  n[        U5       H	  nXeX&   '   M     S/U-  n[        U5       H	  nXgX6   '   M     U R	                  U Vs/ s H  obX5U         PM     sn5      $ s  snf )aM  Return the commutator of ``self`` and ``x``: ``~x*~self*x*self``

If f and g are part of a group, G, then the commutator of f and g
is the group identity iff f and g commute, i.e. fg == gf.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> p = Permutation([0, 2, 3, 1])
>>> x = Permutation([2, 0, 3, 1])
>>> c = p.commutator(x); c
Permutation([2, 1, 3, 0])
>>> c == ~x*~p*x*p
True

>>> I = Permutation(3)
>>> p = [I + i for i in range(6)]
>>> for i in range(len(p)):
...     for j in range(len(p)):
...         c = p[i].commutator(p[j])
...         if p[i]*p[j] == p[j]*p[i]:
...             assert c == I
...         else:
...             assert c != I
...

References
==========

.. [1] https://en.wikipedia.org/wiki/Commutator
r  N)r   r*   r+   r8   r   )rT   r   r   r   r:   invar   invbs           r   
commutatorPermutation.commutator  s    H OOLLFq6Q;FGGvaxqAJ vaxqAJ ||D9Dqqaz]D9::9s   	B#c                 (    U R                   (       a  gg)a  
Gives the signature of the permutation needed to place the
elements of the permutation in canonical order.

The signature is calculated as (-1)^<number of inversions>

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([0, 1, 2])
>>> p.inversions()
0
>>> p.signature()
1
>>> q = Permutation([0,2,1])
>>> q.inversions()
1
>>> q.signature()
-1

See Also
========

inversions
r(   r   )rS  rY   s    r   	signaturePermutation.signature  s    6 <<r>   c           	      v    [        [        U R                   Vs/ s H  n[        U5      PM     snS5      $ s  snf )a  
Computes the order of a permutation.

When the permutation is raised to the power of its
order it equals the identity permutation.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> p = Permutation([3, 1, 5, 2, 4, 0])
>>> p.order()
4
>>> (p**(p.order()))
Permutation([], size=6)

See Also
========

identity, cardinality, length, rank, size
r(   )r   r   r{   r*   )rT   r   s     r   orderPermutation.order		  s1    2 cD4D4DE4D5CJ4DEqIIEs   6
c                 4    [        U R                  5       5      $ )a  
Returns the number of integers moved by a permutation.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> Permutation([0, 3, 2, 1]).length()
2
>>> Permutation([[0, 1], [2, 3]]).length()
4

See Also
========

min, max, support, cardinality, order, rank, size
)r*   r   rY   s    r   lengthPermutation.length$	  s    & 4<<>""r>   c                    U R                   (       a  U R                   nOc[        [        5      nU R                  nU R                   H'  nU[        U5      ==   S-  ss'   U[        U5      -  nM)     U(       a  X!S'   Xl         [        U5      $ )a   Return the cycle structure of the permutation as a dictionary
indicating the multiplicity of each cycle length.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> Permutation(3).cycle_structure
{1: 4}
>>> Permutation(0, 4, 3)(1, 2)(5, 6).cycle_structure
{2: 2, 3: 1}
r(   )_cycle_structurer   r   rh   r{   r*   dict)rT   r`   
singletonsr;   s       r   cycle_structurePermutation.cycle_structure9	  su       &&BS!BJ%%3q6
a
c!f$
 & "1$&!Bxr>   c                 ,    [        U R                  5      $ )a^  
Returns the number of cycles contained in the permutation
(including singletons).

Examples
========

>>> from sympy.combinatorics import Permutation
>>> Permutation([0, 1, 2]).cycles
3
>>> Permutation([0, 1, 2]).full_cyclic_form
[[0], [1], [2]]
>>> Permutation(0, 1)(2, 3).cycles
2

See Also
========
sympy.functions.combinatorial.numbers.stirling
)r*   r   rY   s    r   r~   Permutation.cyclesT	  s    * 4(())r>   c                 p   ^ U R                   m[        U4S j[        [        T5      S-
  5       5       5      $ )a   
Returns the index of a permutation.

The index of a permutation is the sum of all subscripts j such
that p[j] is greater than p[j+1].

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([3, 0, 2, 1, 4])
>>> p.index()
2
c              3   J   >#    U  H  nTU   TUS -      :  d  M  Uv   M     g7f)r(   Nr   )rK   r<   r   s     r   rL   $Permutation.index.<locals>.<genexpr>|	  s'     C/1Q4!AE(?11/s   #	#r(   )r   sumr8   r*   r{  s    @r   indexPermutation.indexk	  s,     OOCeCFQJ/CCCr>   c                 ,    [        U R                  5      $ )aE  
Returns the runs of a permutation.

An ascending sequence in a permutation is called a run [5].


Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([2, 5, 7, 3, 6, 0, 1, 4, 8])
>>> p.runs()
[[2, 5, 7], [3, 6], [0, 1, 4, 8]]
>>> q = Permutation([1,3,2,0])
>>> q.runs()
[[1, 3], [2], [0]]
)r   r   rY   s    r   r   Permutation.runs~	  s    $ DOO$$r>   c                     U R                   n[        U5      nS/US-
  -  n[        US-
  5       H0  nSn[        US-   U5       H  nX   X   :  d  M  US-  nM     XSU'   M2     U$ )a  Return the inversion vector of the permutation.

The inversion vector consists of elements whose value
indicates the number of elements in the permutation
that are lesser than it and lie on its right hand side.

The inversion vector is the same as the Lehmer encoding of a
permutation.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([4, 8, 0, 7, 1, 5, 3, 6, 2])
>>> p.inversion_vector()
[4, 7, 0, 5, 0, 2, 1, 1]
>>> p = Permutation([3, 2, 1, 0])
>>> p.inversion_vector()
[3, 2, 1]

The inversion vector increases lexicographically with the rank
of the permutation, the -ith element cycling through 0..i.

>>> p = Permutation(2)
>>> while p:
...     print('%s %s %s' % (p, p.inversion_vector(), p.rank()))
...     p = p.next_lex()
(2) [0, 0] 0
(1 2) [0, 1] 1
(2)(0 1) [1, 0] 2
(0 1 2) [1, 1] 3
(0 2 1) [2, 0] 4
(0 2) [2, 1] 5

See Also
========

from_inversion_vector
r   r(   )r   r*   r8   )rT   self_array_formr:   inversion_vectorr   valr<   s          r   r  Permutation.inversion_vector	  s|    P // 3!a%=q1uAC1q5!_"%(::1HC % #&Q   r>   c                 b   U R                   / :X  d  U R                  (       a  gU R                   SS/:X  a  gU R                   nU R                  nSn[        SU5       HO  nSnSnX   U:w  a  X   U:  a  US-  nUS-  nX   U:w  a  M  US-   nUS-  S:X  a  Xs-  U-   U-
  nME  Xs-  U-   S-
  nMQ     U$ )ak  
Returns the Trotter Johnson rank, which we get from the minimal
change algorithm. See [4] section 2.4.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.rank_trotterjohnson()
0
>>> p = Permutation([0, 2, 1, 3])
>>> p.rank_trotterjohnson()
7

See Also
========

unrank_trotterjohnson, next_trotterjohnson
r   r(   r)   )r   r_  rh   r8   )rT   r   r:   r   r<   ra   r   j1s           r   rank_trotterjohnsonPermutation.rank_trotterjohnson	  s    * ??b D$4$4??q!f$IIq!AAA'Q,7Q;FAQ 'Q, QBax1}w|a'w{Q  r>   c                 h   S/U-  nSn[        U5      nSn[        SUS-   5       Hz  nXg-  nX&-  U-  nXU-  -
  n	US-  S:X  a3  [        US-
  Xy-
  S-
  S5       H  n
X:S-
     X:'   M     US-
  X7U	-
  S-
  '   O'[        US-
  U	S5       H  n
X:S-
     X:'   M     US-
  X9'   UnM|     U R                  U5      $ )ae  
Trotter Johnson permutation unranking. See [4] section 2.4.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> Permutation.unrank_trotterjohnson(5, 10)
Permutation([0, 3, 1, 2, 4])

See Also
========

rank_trotterjohnson, next_trotterjohnson
r   r(   r)   r   )r   r8   r   )r   rh   r   r   r2r:   pjr<   r1ra   r   s              r   unrank_trotterjohnson!Permutation.unrank_trotterjohnson	  s    & s4xJq$(#AGB)!BrT	AAv{q1uaeai4A"q5kDG 5"#a%UQYq1ua,A"q5kDG -a%B $ {{4  r>   c                    U R                   SS n[        U5      nSnUSS nSnUS-
  nUS:  a  U(       d  UR                  U5      n[        Xv5       H  nXHS-      XH'   M     [	        USU 5      n	U	S:X  a-  Xv:X  a  US-  nOTXU-   S-      XU-      sXU-   '   XU-   S-   '   SnO2US:X  a  US-  nUS-  nO!XU-   S-
     XU-      sXU-   '   XU-   S-
  '   SnUS:  a	  U(       d  M  US:X  a  gU R                  U5      $ )a  
Returns the next permutation in Trotter-Johnson order.
If self is the last permutation it returns None.
See [4] section 2.4. If it is desired to generate all such
permutations, they can be generated in order more quickly
with the ``generate_bell`` function.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> p = Permutation([3, 0, 2, 1])
>>> p.rank_trotterjohnson()
4
>>> p = p.next_trotterjohnson(); p
Permutation([0, 3, 2, 1])
>>> p.rank_trotterjohnson()
5

See Also
========

rank_trotterjohnson, unrank_trotterjohnson, sympy.utilities.iterables.generate_bell
Nr   Fr(   T)r   r*   r  r8   r=   r   )
rT   r9   r:   strI  doner.   dr   pars
             r   next_trotterjohnsonPermutation.next_trotterjohnson
  s0   6 __QGeaC!eD		!A1[U !S!W%Cax6FA13FQJF.BAvJ6A:D6FA!GB13FQJF.BAvJ6A:D# !eDD$ 6||Br>   c                     [        U R                  5      nU R                  n[        UR                  5       H.  n[        US-   UR
                  5       H  nSXU   X$   4'   M     M0     U$ )aF  
Gets the precedence matrix. This is used for computing the
distance between two permutations.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> p = Permutation.josephus(3, 6, 1)
>>> p
Permutation([2, 5, 3, 1, 4, 0])
>>> p.get_precedence_matrix()
Matrix([
[0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 1, 0],
[1, 1, 0, 1, 1, 1],
[1, 1, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 0],
[1, 1, 0, 1, 1, 0]])

See Also
========

get_precedence_distance, get_adjacency_matrix, get_adjacency_distance
r(   )r   rh   r   r8   rowscols)rT   r.   r   r   r<   s        r   get_precedence_matrix!Permutation.get_precedence_matrixM
  s`    8 $))qvvA1q5!&&)&'q'47"# *  r>   c                    U R                   UR                   :w  a  [        S5      eU R                  5       nUR                  5       nSn[        U R                   5       H>  n[        U R                   5       H"  nXV:X  a  M
  X%U4   X5U4   -  S:X  d  M  US-  nM$     M@     U R                   U R                   S-
  -  S-  U-
  nU$ )a!  
Computes the precedence distance between two permutations.

Explanation
===========

Suppose p and p' represent n jobs. The precedence metric
counts the number of times a job j is preceded by job i
in both p and p'. This metric is commutative.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([2, 0, 4, 3, 1])
>>> q = Permutation([3, 1, 2, 4, 0])
>>> p.get_precedence_distance(q)
7
>>> q.get_precedence_distance(p)
7

See Also
========

get_precedence_matrix, get_adjacency_matrix, get_adjacency_distance
r  r   r(   r)   )rh   r+   r  r8   )rT   r_   self_prec_matother_prec_matn_precr   r<   r  s           r   get_precedence_distance#Permutation.get_precedence_distancep
  s    6 99

"FGG224446tyy!A499%6 A&1)==BaKF	 & " IIQ'*V3r>   c                     [        U R                  5      nU R                  n[        U R                  S-
  5       H  nSXU   X#S-      4'   M     U$ )a  
Computes the adjacency matrix of a permutation.

Explanation
===========

If job i is adjacent to job j in a permutation p
then we set m[i, j] = 1 where m is the adjacency
matrix of p.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation.josephus(3, 6, 1)
>>> p.get_adjacency_matrix()
Matrix([
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0]])
>>> q = Permutation([0, 1, 2, 3])
>>> q.get_adjacency_matrix()
Matrix([
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]])

See Also
========

get_precedence_matrix, get_precedence_distance, get_adjacency_distance
r(   )r   rh   r   r8   )rT   r.   r   r   s       r   get_adjacency_matrix Permutation.get_adjacency_matrix
  sO    J $))tyy1}%A&'A1gtE{"# &r>   c                 f   U R                   UR                   :w  a  [        S5      eU R                  5       nUR                  5       nSn[        U R                   5       H>  n[        U R                   5       H"  nXV:X  a  M
  X%U4   X5U4   -  S:X  d  M  US-  nM$     M@     U R                   U-
  S-
  nU$ )a  
Computes the adjacency distance between two permutations.

Explanation
===========

This metric counts the number of times a pair i,j of jobs is
adjacent in both p and p'. If n_adj is this quantity then
the adjacency distance is n - n_adj - 1 [1]

[1] Reeves, Colin R. Landscapes, Operators and Heuristic search, Annals
of Operational Research, 86, pp 473-490. (1999)


Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([0, 3, 1, 2, 4])
>>> q = Permutation.josephus(4, 5, 2)
>>> p.get_adjacency_distance(q)
3
>>> r = Permutation([0, 2, 1, 4, 3])
>>> p.get_adjacency_distance(r)
4

See Also
========

get_precedence_matrix, get_precedence_distance, get_adjacency_matrix
*The permutations must be of the same size.r   r(   )rh   r+   r  r8   )rT   r_   self_adj_matother_adj_matn_adjr   r<   r  s           r   get_adjacency_distance"Permutation.get_adjacency_distance
  s    @ 99

"IJJ002224tyy!A499%61%d(;;q@QJE	 & " II!r>   c                    ^^ U R                   mUR                   m[        T5      [        T5      :w  a  [        S5      e[        UU4S j[	        [        T5      5       5       5      $ )a|  
Computes the positional distance between two permutations.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> p = Permutation([0, 3, 1, 2, 4])
>>> q = Permutation.josephus(4, 5, 2)
>>> r = Permutation([3, 1, 4, 0, 2])
>>> p.get_positional_distance(q)
12
>>> p.get_positional_distance(r)
12

See Also
========

get_precedence_distance, get_adjacency_distance
r  c              3   L   >#    U  H  n[        TU   TU   -
  5      v   M     g 7frI   )absrJ   s     r   rL   6Permutation.get_positional_distance.<locals>.<genexpr>  s%     ;]3qtad{##]s   !$)r   r*   r+   r  r8   r   s     @@r   get_positional_distance#Permutation.get_positional_distance
  sN    * OOq6SVIJJ;U3q6];;;r>   c                    SSK Jn  US-  nU" [        [        U5      5      5      n/ n[	        U5      [        US5      :  ak  [        U5       H"  nUR                  UR                  5       5        M$     UR                  UR                  5       5        [	        U5      [        US5      :  a  Mk  UR                  [        U5      5        U " U5      $ )a  Return as a permutation the shuffling of range(n) using the Josephus
scheme in which every m-th item is selected until all have been chosen.
The returned permutation has elements listed by the order in which they
were selected.

The parameter ``s`` stops the selection process when there are ``s``
items remaining and these are selected by continuing the selection,
counting by 1 rather than by ``m``.

Consider selecting every 3rd item from 6 until only 2 remain::

    choices    chosen
    ========   ======
      012345
      01 345   2
      01 34    25
      01  4    253
      0   4    2531
      0        25314
               253140

Examples
========

>>> from sympy.combinatorics import Permutation
>>> Permutation.josephus(3, 6, 2).array_form
[2, 5, 3, 1, 4, 0]

References
==========

.. [1] https://en.wikipedia.org/wiki/Flavius_Josephus
.. [2] https://en.wikipedia.org/wiki/Josephus_problem
.. [3] https://web.archive.org/web/20171008094331/http://www.wou.edu/~burtonl/josephus.html

r   )dequer(   )	collectionsr  rE   r8   r*   rg   r   popleftr   )r   r.   r:   r   r  Qr   dps           r   josephusPermutation.josephus  s    L 	&	Q$uQx.!!fs1ay Ah% KK		$ !fs1ay  	DG4yr>   c                 8   [        U5      n[        [        US-   5      5      n/ n [        U5       H,  nX1U      nUR                  U5        UR	                  U5        M.     UR                  U5        U R                  U5      $ ! [
         a    [        S5      ef = f)a0  
Calculates the permutation from the inversion vector.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> Permutation.from_inversion_vector([3, 2, 1, 0, 0])
Permutation([3, 2, 1, 0, 4, 5])

r(   z"The inversion vector is not valid.)	r*   rE   r8   r   remove
IndexErrorr+   r   r   )r   	inversionrh   Nr   ra   r  s          r   from_inversion_vector!Permutation.from_inversion_vector>  s     9~tax!	C4[!oC  ! 	A{{4    	CABB	Cs   ;B Bc                 x    [        [        U5      5      n[        R                  " U5        U R	                  U5      $ )z
Generates a random permutation of length ``n``.

Uses the underlying Python pseudo-random number generator.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> Permutation.random(2) in (Permutation([1, 0]), Permutation([0, 1]))
True

)rE   r8   randomshuffler   )r   r:   
perm_arrays      r   r  Permutation.randomZ  s,     %(^
z"{{:&&r>   c                     S/U-  nSn[        U5       HQ  nXES-   -  nX&-  U-  nX'U-  -  nXsX-
  S-
  '   [        X-
  U5       H  nX8   US-
  :  d  M  X8==   S-  ss'   M     UnMS     U R                  U5      $ )aC  
Lexicographic permutation unranking.

Examples
========

>>> from sympy.combinatorics import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> a = Permutation.unrank_lex(5, 10)
>>> a.rank()
10
>>> a
Permutation([0, 2, 4, 1, 3])

See Also
========

rank, next_lex
r   r(   )r8   r   )	r   rh   r   r  rJ  r   	new_psizer  r<   s	            r   r   Permutation.unrank_lexm  s    , S4Z
tA1uI!e+AeGOD'(tx!|$48T*=1q5(MQ&M + E  {{:&&r>   c           	         U R                   n[        U5      nX:  a,  U[        [        X15      5      -  n[        R                  U5      $ X:  a  U R                  n/ nU H`  n[        U5      n[        U5      nXqS-
  ::  d  M#  XS-
  :  a$  [        SR                  U[        U5      5      5      eUR                  U5        Mb     [	        U5      $ U $ )a  Resize the permutation to the new size ``n``.

Parameters
==========

n : int
    The new size of the permutation.

Raises
======

ValueError
    If the permutation cannot be resized to the given size.
    This may only happen when resized to a smaller size than
    the original.

Examples
========

>>> from sympy.combinatorics import Permutation

Increasing the size of a permutation:

>>> p = Permutation(0, 1, 2)
>>> p = p.resize(5)
>>> p
(4)(0 1 2)

Decreasing the size of the permutation:

>>> p = p.resize(4)
>>> p
(3)(0 1 2)

If resizing to the specific size breaks the cycles:

>>> p.resize(2)
Traceback (most recent call last):
...
ValueError: The permutation cannot be resized to 2 because the
cycle (0, 1, 2) may break.
r(   zGThe permutation cannot be resized to {} because the cycle {} may break.)r   r*   rE   r8   rz   r   r   r  rg   r+   r'  rp   r   )	rT   r:   r   lr{   new_cyclic_formr   	cycle_min	cycle_maxs	            r   resizePermutation.resize  s    V J5T%+&&E&&u--U//K O$J	J	!# Q3(>#VAuU|46 6
 $**51 % //r>   )r  r   r   rI   )r(   )Xr   r   r   r   r   is_Permutationr   r   r  r   r   r   classmethodr   r   r   r   r   r   rE   r{   r   rh   r   r   r   staticmethodr   r   r   r   r   r   r  r  r
  r  r  r  rZ   r   rc   r*  r0  r3  r;  rC  rF  r   r   rO  rS  rR  rY  r\  r`  r_  rl  rq  r   rg   r  r  r  r  r  r  r  r~   r  r   r  r  r  r  r  r  r  r  r  r  r  r  r   r  print_cyclicr   __classcell__r   s   @r   rz   rz     s   bH NKLEE!% |"|  2/"&
 # #&&P ( (T    $6 4$ * *X  ,
?"B'(9,@"N`&P 0 0.:,
#';R$/+b)"V % %@"H48#J $ $&+@  , ' ',  *  (     C C:,,<S <,<S <,:x/;b>J6#*  4 * *,D&%(2 h(T #! #!J5 n!F'R)V,\<6 . .` ! !6 ' '$  '  'DAH Lr>   rz   c                 B   U=pVUnSnXS:  aC  Xt::  a>  X   X   :  a  X   X'   US-  nUS-  nOX   X'   US-  nUS-  nXU-
  -  nXS:  a  Xt::  a  M>  XS:  a  X   X'   US-  nUS-  nXS:  a  M  Xt::  a"  XdU-
  S-   -  nXtU-
  S-   -  nXUS-    XUS-   & U$ XUS-    XUS-   & U$ )z
Merges two sorted arrays and calculates the inversion count.

Helper function for calculating inversions. This method is
for internal use only.
r   r(   r   )	r  r   leftmidr  r   ra   r<   	inv_counts	            r   r  r    s    LAAI
'aj6CF?fDGFAFAfDGFAFAq&!I 'aj '&	Q	Q ' 	z	QY]	QY]AE*Q  #	2r>   c                   0   ^  \ rS rSrSrSU 4S jjrSrU =r$ )r/  i  am  A permutation applied to a symbolic variable.

Parameters
==========

perm : Permutation
x : Expr

Examples
========

>>> from sympy import Symbol
>>> from sympy.combinatorics import Permutation

Creating a symbolic permutation function application:

>>> x = Symbol('x')
>>> p = Permutation(0, 1, 2)
>>> p.apply(x)
AppliedPermutation((0 1 2), x)
>>> _.subs(x, 1)
2
c                 *  > Uc  [         R                  n[        U5      n[        U5      n[        U[        5      (       d  [        SR                  U5      5      eU(       a"  UR                  (       a  UR                  U5      $ [        TU ])  XU5      nU$ )Nz"{} must be a Permutation instance.)r   evaluater   r   rz   r+   r'  r.  r0  r   r   )r   r   r   r  objr   s        r   r   AppliedPermutation.__new__  s{    (11H~QK$,,A  ||zz!}$goc+
r>   r   rI   )r   r   r   r   r   r   r   r  r  s   @r   r/  r/    s    . r>   r/  c                 j    U R                   UR                   :w  a  g U R                  UR                  :H  $ rI   )r   r   )lhsrhss     r   _eval_is_eqr	  &  s(    
yyCII??coo--r>   )3r  r  r   collections.abcr   	functoolsr   sympy.core.parametersr   sympy.core.basicr   sympy.core.exprr   sympy.core.numbersr	   r
   sympy.core.sympifyr   sympy.matricesr   sympy.polys.polytoolsr   sympy.printing.reprr   sympy.utilities.iterablesr   r   r   r   r   r   sympy.utilities.miscr   mpmath.libmp.libintmathr   sympy.multipledispatchr   r    r,   r=   rC   rF   rO   r  rQ   rz   r  Permr   r/  r	  r   r>   r   <module>r     s     # $  3 !   ) & '   % %! ! ' ( +B:z$N2*ZB(bD bJ{'$ {'|O@ 
,,( (V 
+{#. $.r>   