
    wgS                       d dl mZmZmZ d dlmZmZ d dlm	Z	 d dl
mZmZmZmZmZmZ d dlmZmZmZmZmZmZmZmZ d dlmZ d dlmZmZmZ d dl m!Z! d d	l"m#Z# d d
l$mZ d dl%m&Z&m'Z' d dl(m)Z)m*Z* d dl+m,Z, d dl-m.Z.m/Z/m0Z0 e	jb                  Z2e	jf                  Z3 G d de      Z4ddZ5d Z6ddZ7d Z8e4Z9 G d de      Z: G d de      Z;y)    )	factoriallogprod)chainproduct)Permutation)_af_commutes_with
_af_invert_af_rmul	_af_rmuln_af_powCycle)_check_cycles_alt_sym_distribute_gens_by_base_orbits_transversals_from_bsgs_handle_precomputed_bsgs_base_ordering_strong_gens_from_distr_strip	_strip_af)Basic)
_randrange	randrangechoice)Symbol)_sympify)r   )primefactorssieve)	factorintmultiplicity)isprime)has_varietyis_sequenceuniqc                   j   e Zd ZdZdZdddZd Zd Zd Zd Z	d	 Z
d
 ZdadZd Zd Zed        Z	 	 dbdZed        Zed        Zed        Zd Zd Zd Zd Zd Zd Zd ZdcdZdcdZd ZdcdZed        Z ed         Z!ed!        Z"d" Z#d# Z$ddd$Z%dcd%Z&dcd&Z'ed'        Z(ded(Z)ed)        Z*ed*        Z+d+ Z,d, Z-dfd-Z.dgd.Z/dgd/Z0ed0        Z1ded1Z2ded2Z3ded3Z4ed4        Z5ded5Z6ed6        Z7ded7Z8ed8        Z9d9 Z:ed:        Z;d; Z<d< Z=d= Z>dhd>Z?did?Z@dad@ZAdcdAZBdcdBZCdC ZDdD ZEedE        ZFedF        ZGeHdG        ZIedH        ZJedI        ZKdedJZLdadKZMdcdLZNdjdMZOdkdNZPdO ZQdadPZRdldQZS	 	 dmdRZTdS ZUdT ZVedU        ZWdV ZX	 	 dndWZYedX        ZZdY Z[dZ Z\d[ Z]d\ Z^d] Z_d^ Z`ded_Zad` Zby)oPermutationGroupaJ  The class defining a Permutation group.

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

    ``PermutationGroup([p1, p2, ..., pn])`` returns the permutation group
    generated by the list of permutations. This group can be supplied
    to Polyhedron if one desires to decorate the elements to which the
    indices of the permutation refer.

    Examples
    ========

    >>> from sympy.combinatorics import Permutation, PermutationGroup
    >>> from sympy.combinatorics import Polyhedron

    The permutations corresponding to motion of the front, right and
    bottom face of a $2 \times 2$ Rubik's cube are defined:

    >>> F = Permutation(2, 19, 21, 8)(3, 17, 20, 10)(4, 6, 7, 5)
    >>> R = Permutation(1, 5, 21, 14)(3, 7, 23, 12)(8, 10, 11, 9)
    >>> D = Permutation(6, 18, 14, 10)(7, 19, 15, 11)(20, 22, 23, 21)

    These are passed as permutations to PermutationGroup:

    >>> G = PermutationGroup(F, R, D)
    >>> G.order()
    3674160

    The group can be supplied to a Polyhedron in order to track the
    objects being moved. An example involving the $2 \times 2$ Rubik's cube is
    given there, but here is a simple demonstration:

    >>> a = Permutation(2, 1)
    >>> b = Permutation(1, 0)
    >>> G = PermutationGroup(a, b)
    >>> P = Polyhedron(list('ABC'), pgroup=G)
    >>> P.corners
    (A, B, C)
    >>> P.rotate(0) # apply permutation 0
    >>> P.corners
    (A, C, B)
    >>> P.reset()
    >>> P.corners
    (A, B, C)

    Or one can make a permutation as a product of selected permutations
    and apply them to an iterable directly:

    >>> P10 = G.make_perm([0, 1])
    >>> P10('ABC')
    ['C', 'A', 'B']

    See Also
    ========

    sympy.combinatorics.polyhedron.Polyhedron,
    sympy.combinatorics.permutations.Permutation

    References
    ==========

    .. [1] Holt, D., Eick, B., O'Brien, E.
           "Handbook of Computational Group Theory"

    .. [2] Seress, A.
           "Permutation Group Algorithms"

    .. [3] https://en.wikipedia.org/wiki/Schreier_vector

    .. [4] https://en.wikipedia.org/wiki/Nielsen_transformation#Product_replacement_algorithm

    .. [5] Frank Celler, Charles R.Leedham-Green, Scott H.Murray,
           Alice C.Niemeyer, and E.A.O'Brien. "Generating Random
           Elements of a Finite Group"

    .. [6] https://en.wikipedia.org/wiki/Block_%28permutation_group_theory%29

    .. [7] https://algorithmist.com/wiki/Union_find

    .. [8] https://en.wikipedia.org/wiki/Multiply_transitive_group#Multiply_transitive_groups

    .. [9] https://en.wikipedia.org/wiki/Center_%28group_theory%29

    .. [10] https://en.wikipedia.org/wiki/Centralizer_and_normalizer

    .. [11] https://groupprops.subwiki.org/wiki/Derived_subgroup

    .. [12] https://en.wikipedia.org/wiki/Nilpotent_group

    .. [13] https://www.math.colostate.edu/~hulpke/CGT/cgtnotes.pdf

    .. [14] https://docs.gap-system.org/doc/ref/manual.pdf

    T)dupsc                   |st               g}n+t        t        |d         r|d   n|      }|st               g}t        d |D              r|D cg c]  }t        |       }}t	        d |D              re|j                  dd      }|t        d |D              }t        t        |            D ](  }||   j                  |k7  st        ||   |      ||<   * |r4t        t        |D cg c]  }t        t        |             c}            }t        |      dkD  r|D cg c]  }|j                  r| }}t        j                  | g|i |S c c}w c c}w c c}w )	zThe default constructor. Accepts Cycle and Permutation forms.
        Removes duplicates unless ``dups`` keyword is ``False``.
        r   c              3   <   K   | ]  }t        |t                y wN)
isinstancer   .0as     d/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/combinatorics/perm_groups.py	<genexpr>z+PermutationGroup.__new__.<locals>.<genexpr>   s     2z!U#2s   c              3   4   K   | ]  }|j                     y wr*   sizer,   s     r/   r0   z+PermutationGroup.__new__.<locals>.<genexpr>   s     ,!qvv,   degreeNc              3   4   K   | ]  }|j                     y wr*   r2   r,   s     r/   r0   z+PermutationGroup.__new__.<locals>.<genexpr>   s     2QVV2r4   r2      )r   listr#   anyr"   popmaxrangelenr3   r$   _af_newis_identityr   __new__)clsr'   argskwargsr.   r5   igs           r/   r@   zPermutationGroup.__new__|   s?    M?D;tAw#7QTBD#2T22,01qKN1D1,t,,ZZ$/F~2T223t9% @7<<6))$q'?DG@ =1gd1g.=>?Dt9q=#9!1==A9D9}}S242622 2 >9s   E+E#E5Ec                    t        | j                        | _        d | _        g | _        d | _        d | _        d | _        d | _        d | _	        d | _
        d | _        d | _        d | _        d | _        d | _        d | _        d | _        d | _        t'        | j                        | _        | j                  d   j*                  | _        g | _        g | _        g | _        g | _        g | _        g | _        g | _        d | _        y Nr   )r8   rB   _generators_order	_elements_center_is_abelian_is_transitive_is_sym_is_alt_is_primitive_is_nilpotent_is_solvable_is_trivial_transitivity_degree_max_div_is_perfect
_is_cyclic_is_dihedralr=   _rr3   _degree_base_strong_gens_strong_gens_slp_basic_orbits_transversals_transversal_slp_random_gens_fp_presentationselfrB   rC   s      r/   __init__zPermutationGroup.__init__   s    		?"!! $(! d&&'''*// 
 " "  !%    c                      | j                   |   S r*   rH   rd   rD   s     r/   __getitem__zPermutationGroup.__getitem__   s    ""rf   c                 r    t        |t              st        dt        |      z        | j	                  |      S )a  Return ``True`` if *i* is contained in PermutationGroup.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> p = Permutation(1, 2, 3)
        >>> Permutation(3) in PermutationGroup(p)
        True

        zRA PermutationGroup contains only Permutations as elements, not elements of type %s)r+   r   	TypeErrortypecontainsri   s     r/   __contains__zPermutationGroup.__contains__   s?     ![) @BFq'J K K}}Qrf   c                 ,    t        | j                        S r*   )r=   rH   rd   s    r/   __len__zPermutationGroup.__len__   s    4##$$rf   c                     t        |t              syt        | j                        }t        |j                        }||k(  ry|D ]  }|j	                  |      r y |D ]  }| j	                  |      r y y)a  Return ``True`` if PermutationGroup generated by elements in the
        group are same i.e they represent the same PermutationGroup.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> p = Permutation(0, 1, 2, 3, 4, 5)
        >>> G = PermutationGroup([p, p**2])
        >>> H = PermutationGroup([p**2, p])
        >>> G.generators == H.generators
        False
        >>> G.equals(H)
        True

        FT)r+   r&   set
generatorsrn   )rd   otherset_self_gensset_other_gensgen1gen2s         r/   equalszPermutationGroup.equals   s    " %!12DOO,U--.
 N* " 	D>>$'	 # 	D==&	 rf   c                    t        |t              rt        || d      S | j                  D cg c]  }|j                   }}|j                  D cg c]  }|j                   }}| j
                  }|j
                  }t        t        |            }t        t        |||z               }t        t        |            D ]  }	||	   D 
cg c]  }
|
|z   	 c}
||	<    |D cg c]  }||z   	 }}|D cg c]  }||z   	 }}||z   }|D 
cg c]  }
t        |
       }}
t        |      S c c}w c c}w c c}
w c c}w c c}w c c}
w )a  
        Return the direct product of two permutation groups as a permutation
        group.

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

        This implementation realizes the direct product by shifting the index
        set for the generators of the second group: so if we have ``G`` acting
        on ``n1`` points and ``H`` acting on ``n2`` points, ``G*H`` acts on
        ``n1 + n2`` points.

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import CyclicGroup
        >>> G = CyclicGroup(5)
        >>> H = G*G
        >>> H
        PermutationGroup([
            (9)(0 1 2 3 4),
            (5 6 7 8 9)])
        >>> H.order()
        25

        +)dir)r+   r   Cosetru   _array_formrZ   r8   r<   r=   r>   r&   )rd   rv   permgens1gens2n1n2startendrD   xgentogethergenss                 r/   __mul__zPermutationGroup.__mul__   s0   6 e[)#...2oo>d!!>>.3.>.>?d!!??\\]]U2Y5R"W%&s5z" 	2A(-a11B1E!H	2(-...&+,ss,,5=$,-q
--%% ?? 2.,-s#   D'D,D1D61D;E Nc                    | j                   }| j                  D cg c]  }|j                   }}t        |      }||k  r(t	        ||      D ]  }|j                  |||z
             t        t	        |            }	|j                  |	       || _        |!t	        |      D ]  }| j                           yt	        |      D ]  }| j                  ||           yc c}w )a  Initialize random generators for the product replacement algorithm.

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

        The implementation uses a modification of the original product
        replacement algorithm due to Leedham-Green, as described in [1],
        pp. 69-71; also, see [2], pp. 27-29 for a detailed theoretical
        analysis of the original product replacement algorithm, and [4].

        The product replacement algorithm is used for producing random,
        uniformly distributed elements of a group `G` with a set of generators
        `S`. For the initialization ``_random_pr_init``, a list ``R`` of
        `\max\{r, |S|\}` group generators is created as the attribute
        ``G._random_gens``, repeating elements of `S` if necessary, and the
        identity element of `G` is appended to ``R`` - we shall refer to this
        last element as the accumulator. Then the function ``random_pr()``
        is called ``n`` times, randomizing the list ``R`` while preserving
        the generation of `G` by ``R``. The function ``random_pr()`` itself
        takes two random elements ``g, h`` among all elements of ``R`` but
        the accumulator and replaces ``g`` with a randomly chosen element
        from `\{gh, g(~h), hg, (~h)g\}`. Then the accumulator is multiplied
        by whatever ``g`` was replaced by. The new value of the accumulator is
        then returned by ``random_pr()``.

        The elements returned will eventually (for ``n`` large enough) become
        uniformly distributed across `G` ([5]). For practical purposes however,
        the values ``n = 50, r = 11`` are suggested in [1].

        Notes
        =====

        THIS FUNCTION HAS SIDE EFFECTS: it changes the attribute
        self._random_gens

        See Also
        ========

        random_pr

        N)_random_prec)	r5   ru   r   r=   r<   appendr8   ra   	random_pr)
rd   rn_random_prec_ndegr   random_genskrD   accs
             r/   _random_pr_initz PermutationGroup._random_pr_init!  s    T kk.2oo>q}}>>q51a[ 7"";q1u#5675:3' !1X ! ! 1X ?N1,=>? ?s   Cc                     | j                  ||      }| j                  ||      }||k7  rK||   ||   k\  r||}	}n||}	}||   ||	   z   }
|
| j                  kD  ry|||	<   |
||<   |j                  |	       yy)aC  Merges two classes in a union-find data structure.

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

        Used in the implementation of Atkinson's algorithm as suggested in [1],
        pp. 83-87. The class merging process uses union by rank as an
        optimization. ([7])

        Notes
        =====

        THIS FUNCTION HAS SIDE EFFECTS: the list of class representatives,
        ``parents``, the list of class sizes, ``ranks``, and the list of
        elements that are not representatives, ``not_rep``, are changed due to
        class merging.

        See Also
        ========

        minimal_block, _union_find_rep

        References
        ==========

        .. [1] Holt, D., Eick, B., O'Brien, E.
               "Handbook of computational group theory"

        .. [7] https://algorithmist.com/wiki/Union_find

        r7   r   )_union_find_repmax_divr   )rd   firstsecondranksparentsnot_rep	rep_first
rep_secondnew_1new_2
total_ranks              r/   _union_find_mergez"PermutationGroup._union_find_merge]  s    @ ((8	))&':

"Y5#44(*u)9uue4JDLL("GEN%E%LNN5!rf   c                 t    |||   }}||k7  r|}||   }||k7  r|||   }}||k7  r|||<   |}||   }||k7  r|S )a  Find representative of a class in a union-find data structure.

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

        Used in the implementation of Atkinson's algorithm as suggested in [1],
        pp. 83-87. After the representative of the class to which ``num``
        belongs is found, path compression is performed as an optimization
        ([7]).

        Notes
        =====

        THIS FUNCTION HAS SIDE EFFECTS: the list of class representatives,
        ``parents``, is altered due to path compression.

        See Also
        ========

        minimal_block, _union_find_merge

        References
        ==========

        .. [1] Holt, D., Eick, B., O'Brien, E.
               "Handbook of computational group theory"

        .. [7] https://algorithmist.com/wiki/Union_find

         )rd   numr   repparenttemps         r/   r   z PermutationGroup._union_find_rep  sl    > 73<VmCS\F m GCLfmGDMDT]F m 
rf   c                 X    | j                   g k(  r| j                          | j                   S )a  Return a base from the Schreier-Sims algorithm.

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

        For a permutation group `G`, a base is a sequence of points
        `B = (b_1, b_2, \dots, b_k)` such that no element of `G` apart
        from the identity fixes all the points in `B`. The concepts of
        a base and strong generating set and their applications are
        discussed in depth in [1], pp. 87-89 and [2], pp. 55-57.

        An alternative way to think of `B` is that it gives the
        indices of the stabilizer cosets that contain more than the
        identity permutation.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> G = PermutationGroup([Permutation(0, 1, 3)(2, 4)])
        >>> G.base
        [0, 2]

        See Also
        ========

        strong_gens, basic_transversals, basic_orbits, basic_stabilizers

        )r[   schreier_simsrq   s    r/   basezPermutationGroup.base  s&    > :: zzrf   c           
      $   t        |||||      \  }}}t        |      }| j                  }	t        ||         t        ||dz            z  t        t        |	||   ||dz                  z  }
|dz   |dz
  kD  rg }n||dz      dd }|du rt	        ||         }|j                  ||dz            }t        t        |	|||               |
k7  rs|j                  ||dz      |      }|j                  |       t        t        |	|||               |
k7  rGn*t        ||         }|j                  ||          ||dz      |v r|j                  ||dz             t        t        |	|||               |
k7  rt        t        |            }||   |   }|j                  j                  ||dz            }|||dz      vr|t        |	||      z
  }nV||dz      |   }t        ||      } |||         t        |	|||         vr$|j                  |       |t        |	|||         z
  }t        t        |	|||               |
k7  r|dd }|||dz   <   |dd }||dz      ||   c||<   ||dz   <   t        |      }|D ]  }||vs|j                  |        ||fS )a	  Swap two consecutive base points in base and strong generating set.

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

        If a base for a group `G` is given by `(b_1, b_2, \dots, b_k)`, this
        function returns a base `(b_1, b_2, \dots, b_{i+1}, b_i, \dots, b_k)`,
        where `i` is given by ``pos``, and a strong generating set relative
        to that base. The original base and strong generating set are not
        modified.

        The randomized version (default) is of Las Vegas type.

        Parameters
        ==========

        base, strong_gens
            The base and strong generating set.
        pos
            The position at which swapping is performed.
        randomized
            A switch between randomized and deterministic version.
        transversals
            The transversals for the basic orbits, if known.
        basic_orbits
            The basic orbits, if known.
        strong_gens_distr
            The strong generators distributed by basic stabilizers, if known.

        Returns
        =======

        (base, strong_gens)
            ``base`` is the new base, and ``strong_gens`` is a generating set
            relative to it.

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import SymmetricGroup
        >>> from sympy.combinatorics.testutil import _verify_bsgs
        >>> from sympy.combinatorics.perm_groups import PermutationGroup
        >>> S = SymmetricGroup(4)
        >>> S.schreier_sims()
        >>> S.base
        [0, 1, 2]
        >>> base, gens = S.baseswap(S.base, S.strong_gens, 1, randomized=False)
        >>> base, gens
        ([0, 2, 1],
        [(0 1 2 3), (3)(0 1), (1 3 2),
         (2 3), (1 3)])

        check that base, gens is a BSGS

        >>> S1 = PermutationGroup(gens)
        >>> _verify_bsgs(S1, base, gens)
        True

        See Also
        ========

        schreier_sims

        Notes
        =====

        The deterministic version of the algorithm is discussed in
        [1], pp. 102-103; the randomized version is discussed in [1], p.103, and
        [2], p.98. It is of Las Vegas type.
        Notice that [1] contains a mistake in the pseudocode and
        discussion of BASESWAP: on line 3 of the pseudocode,
        `|\beta_{i+1}^{\left\langle T\right\rangle}|` should be replaced by
        `|\beta_{i}^{\left\langle T\right\rangle}|`, and the same for the
        discussion of the algorithm.

        r7      NT)schreier_vector)r   r=   r5   _orbitr&   r   random_stabr   rt   removenextiterr   indexrmulr   )rd   r   strong_genspos
randomizedtransversalsbasic_orbitsstrong_gens_distrbase_lenr5   r3   Tstab_posr   newGammagammar   r   yelstrong_gens_new_distrbase_newstrong_gens_newr   s                            r/   baseswapzPermutationGroup.baseswap  s    b %T;!-/@B 	6l$5 t9 <$%c,sQw*?&@@&!23!7cAgGHI 7X\!A!#'*1-A'(9#(>?H&66tC!G}EOfVQS	23t;**4a=;J + L fVQS	23t; S)*ELLc#C!G}%T#']+ fVQS	23t;T%[) %e,}}**4a=9|C!G44!F61e$<<E$S1W-d3AaB$s)}F61d3i,HH %vq$s)(D D fVQS	23t; !2! 4)*cAg&7+3C!G+<hsm(xa(12GH 	,C/)&&s+	, ((rf   c                 X    | j                   g k(  r| j                          | j                   S )a  
        Return the basic orbits relative to a base and strong generating set.

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

        If `(b_1, b_2, \dots, b_k)` is a base for a group `G`, and
        `G^{(i)} = G_{b_1, b_2, \dots, b_{i-1}}` is the ``i``-th basic stabilizer
        (so that `G^{(1)} = G`), the ``i``-th basic orbit relative to this base
        is the orbit of `b_i` under `G^{(i)}`. See [1], pp. 87-89 for more
        information.

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import SymmetricGroup
        >>> S = SymmetricGroup(4)
        >>> S.basic_orbits
        [[0, 1, 2, 3], [1, 2, 3], [2, 3]]

        See Also
        ========

        base, strong_gens, basic_transversals, basic_stabilizers

        )r^   r   rq   s    r/   r   zPermutationGroup.basic_orbitsb  s*    8 # !!!rf   c                     | j                   g k(  r| j                          | j                  }| j                  }|sg S t	        ||      }g }|D ]  }|j                  t        |              |S )aD  
        Return a chain of stabilizers relative to a base and strong generating
        set.

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

        The ``i``-th basic stabilizer `G^{(i)}` relative to a base
        `(b_1, b_2, \dots, b_k)` is `G_{b_1, b_2, \dots, b_{i-1}}`. For more
        information, see [1], pp. 87-89.

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import AlternatingGroup
        >>> A = AlternatingGroup(4)
        >>> A.schreier_sims()
        >>> A.base
        [0, 1]
        >>> for g in A.basic_stabilizers:
        ...     print(g)
        ...
        PermutationGroup([
            (3)(0 1 2),
            (1 2 3)])
        PermutationGroup([
            (1 2 3)])

        See Also
        ========

        base, strong_gens, basic_orbits, basic_transversals

        )r_   r   r\   r[   r   r   r&   )rd   r   r   r   basic_stabilizersr   s         r/   r   z"PermutationGroup.basic_stabilizers  sw    J # ''zzI4T;G% 	=D$$%5d%;<	=  rf   c                 X    | j                   g k(  r| j                          | j                   S )a,  
        Return basic transversals relative to a base and strong generating set.

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

        The basic transversals are transversals of the basic orbits. They
        are provided as a list of dictionaries, each dictionary having
        keys - the elements of one of the basic orbits, and values - the
        corresponding transversal elements. See [1], pp. 87-89 for more
        information.

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import AlternatingGroup
        >>> A = AlternatingGroup(4)
        >>> A.basic_transversals
        [{0: (3), 1: (3)(0 1 2), 2: (3)(0 2 1), 3: (0 3 1)}, {1: (3), 2: (1 2 3), 3: (1 3 2)}]

        See Also
        ========

        strong_gens, base, basic_orbits, basic_stabilizers

        )r_   r   rq   s    r/   basic_transversalsz#PermutationGroup.basic_transversals  s*    : # !!!rf   c           
         | j                         }t        d |d   j                  D              st        d      g }t	        t        |      dz
        D ]  }||dz      }g }||   j                  D ]  }t        |g|j                  z         }|j                         |j                         z  }g }	t        |      j                         D ]B  \  }
}t	        |      D ]/  }|	j                  t        |g|j                  z                ||
z  }1 D |	|z   }|} ||   |d<   |j                  |        |j                  |d          |S )a  
        Return the composition series for a group as a list
        of permutation groups.

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

        The composition series for a group `G` is defined as a
        subnormal series `G = H_0 > H_1 > H_2 \ldots` A composition
        series is a subnormal series such that each factor group
        `H(i+1) / H(i)` is simple.
        A subnormal series is a composition series only if it is of
        maximum length.

        The algorithm works as follows:
        Starting with the derived series the idea is to fill
        the gap between `G = der[i]` and `H = der[i+1]` for each
        `i` independently. Since, all subgroups of the abelian group
        `G/H` are normal so, first step is to take the generators
        `g` of `G` and add them to generators of `H` one by one.

        The factor groups formed are not simple in general. Each
        group is obtained from the previous one by adding one
        generator `g`, if the previous group is denoted by `H`
        then the next group `K` is generated by `g` and `H`.
        The factor group `K/H` is cyclic and it's order is
        `K.order()//G.order()`. The series is then extended between
        `K` and `H` by groups generated by powers of `g` and `H`.
        The series formed is then prepended to the already existing
        series.

        Examples
        ========
        >>> from sympy.combinatorics.named_groups import SymmetricGroup
        >>> from sympy.combinatorics.named_groups import CyclicGroup
        >>> S = SymmetricGroup(12)
        >>> G = S.sylow_subgroup(2)
        >>> C = G.composition_series()
        >>> [H.order() for H in C]
        [1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1]
        >>> G = S.sylow_subgroup(3)
        >>> C = G.composition_series()
        >>> [H.order() for H in C]
        [243, 81, 27, 9, 3, 1]
        >>> G = CyclicGroup(12)
        >>> C = G.composition_series()
        >>> [H.order() for H in C]
        [12, 6, 3, 1]

        c              3   4   K   | ]  }|j                     y wr*   )r?   r-   rE   s     r/   r0   z6PermutationGroup.composition_series.<locals>.<genexpr>  s     =Q1===r4   r   zGroup should be solvabler7   r   )derived_seriesallru   NotImplementedErrorr<   r=   r&   orderr   itemsr   extend)rd   derseriesrD   Hup_segrE   Kr   down_segpe_s                r/   composition_seriesz#PermutationGroup.composition_series  sP   f !!#=#b'*<*<==%&@AAs3xz" 	"AAaCAFV&& 	$aS1<<%78	QWWY.%e,224 !DAq"1X ! (8!q||9K(LMqD!! "F*	 AF1IMM&!	" 	c"grf   c                    |j                  |       st        d      |j                         dk(  r| j                  S | j	                  |j
                         | j
                  t        | j                        t        | j                  dz
        }| j                  dd }t        |      D ](  \  }t        |j                         fd      |<   * |j                  }|j                  }| j                  }t        ||      D 	cg c]&  \  }}	|j                         |	j                         z  ( }
}}	t!        |      t!        |      kD  r|t!        |         j                  }n|g}t!        |      dz
  t!        |      }dkD  rg }|   D ]u  }||k(  r	   |z     |D ]G  }||z  t#        fd|   D              r|j%                         |t!        |      z   |
   k(  sG n |t!        |      z   |
   k(  su n ||z  }|t!        |      z  }dz  dkD  r|j'                  |       |g|z   }|S c c}	}w )	zReturn a transversal of the right cosets of self by its subgroup H
        using the second method described in [1], Subsection 4.6.7

        The argument must be a subgroupr7   r   Nc                        | z     S r*   r   )r   r   base_orderingls    r/   <lambda>z4PermutationGroup.coset_transversal.<locals>.<lambda>6  s    d1gai0H rf   keyr   c              3   4   K   | ]  }|z     k\    y wr*   r   )r-   hbr   r   s     r/   r0   z5PermutationGroup.coset_transversal.<locals>.<genexpr>P  s     Fq=1-2F   )is_subgroup
ValueErrorr   elements_schreier_simsr   r   r5   r   r   	enumeratesortedvaluesr   r   zipr=   r   r   r   )rd   r   identityr   torbitsh_stabsg_stabsr   r   indicesr   t_lenT_nextur   r   r   r   r   s                  @@@@@r/   coset_transversalz"PermutationGroup.coset_transversal  s?    }}T">??779>== (yy&tT[[9t{{Q/..q1 l+ 	JDAq$QXXZ&HJLO	J %%((474IJDAq1779aggi'JJ w<#g,&G%..A
ALNA"fF!!_ =!$q'!), A!AFF1IFFa(s6{*gaj8 3v;&'!*4 KAS[ EFA! "f" 	
JN? Ks   +Ic                 .  	 |j                         dk(  r|S | j                  dt        |j                         |j                  k(  s| j                  |j                         |j                  dd |j
                  D cg c]  }t        |j                                c}| j
                  D cg c]  }t        |j                                c}	| j                  t        | j                        	fd d|      S c c}w c c}w )zReturn the representative of Hg from the transversal that
        would be computed by ``self.coset_transversal(H)``.

        r7   Nr   c                 (   t        	|    fd      }|    D cg c]
  }|    |z   c}j                  |      }|    |   z  | t        	      dz
  k  r2|    D ]  }|    |z  |    z  k(  s n  
| dz   dz  z        |z  S c c}w )Nc                     | z     S r*   r   )r   r   r   s    r/   r   zFPermutationGroup._coset_representative.<locals>.step.<locals>.<lambda>m  s    =13E rf   r   r7   r   )minr   r=   )r   r   r   r   rD   r  r   r   h_transversalsr   stepr   s    `    r/   r	  z4PermutationGroup._coset_representative.<locals>.stepl  s    q	)EFE$21$56qa6<<UCAq!!$Q&A3v;q= %a AAwqyDGAI- 1a2g&q(H 7s   Br   )
r   r   r=   r   r   r   r8   r   r   r5   )
rd   rE   r   r   r   r   r  r   r	  r   s
       @@@@@@r/   _coset_representativez&PermutationGroup._coset_representative]  s    
 779>Hyy#aff+&!&&0QVV,"454H4HIq$qxxz*I262I2IJQQXXZ(Jyy&tT[[9		 		 Aqz JJs    D5 Dc                    |j                  |       st        d      | j                  |      }t        |      }t	        t        j                  d | j                  D                    }g }t        |      D ]V  }|D cg c]  }| j                  ||   |z  |       }}|D 	cg c]  }	|j                  |	       }}	|j                  |       X t        t        |            }d}
t        t        |      |      D ]  \  }}||   |   }||
k\  rg||
kD  r]|D ]X  }||
   |   }||   |   ||
   |<   |||   |<   t        |      D ]*  }||   |   |k(  r	|
||   |<   ||   |   |
k(  s#|||   |<   , Z |
dz  }
|
|dz
  k\  s|c S  yc c}w c c}	w )z]Return the standardised (right) coset table of self in H as
        a list of lists.
        r   c              3   *   K   | ]  }||d z  f  yw)r   Nr   )r-   r   s     r/   r0   z/PermutationGroup.coset_table.<locals>.<genexpr>  s       %0 '*37^ %0s   r7   N)r   r   r  r=   r8   r   from_iterableru   r<   r
  r   r   r   )rd   r   r   r   AtablerD   r   rowr   r   alphar.   betazs                  r/   coset_tablezPermutationGroup.coset_tablex  s    }}T">??""1%F$$ %0#%0 0 1 q 	ABCDQ4--ad1fa8DCD'*+!1771:+C+LL	 #a&Ma!, 	HE1<?Du}%< 3!%LO*/+a.eQ)*dA!&q 3A$Qx{d2.3a!&q!!5.2a	3	3 
!|	 E+s   <F!Fc                 ^    | j                   s| j                  |       | _         | j                   S )a  
        Return the center of a permutation group.

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

        The center for a group `G` is defined as
        `Z(G) = \{z\in G | \forall g\in G, zg = gz \}`,
        the set of elements of `G` that commute with all elements of `G`.
        It is equal to the centralizer of `G` inside `G`, and is naturally a
        subgroup of `G` ([9]).

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import DihedralGroup
        >>> D = DihedralGroup(4)
        >>> G = D.center()
        >>> G.order()
        2

        See Also
        ========

        centralizer

        Notes
        =====

        This is a naive implementation that is a straightforward application
        of ``.centralizer()``

        )rK   centralizerrq   s    r/   centerzPermutationGroup.center  s(    D ||++D1DL||rf   c                 ~   t        d      rӉj                  s| j                  r| S | j                  }t        t	        t        |                  }j                         }t        |      }|j                  d        g }dg|z  dg|z  }dg|z  t        |      D ]7  }t	        ||         }	|	d   |<   t        |      ||<   |	D ]  }
||
<   	 ||	z   }9 | j                  |      \  }t        |      }d}t        t                    D ]  }||   |gk(  s n d| |}t        |      D ]  }|dz
     ||   v s n |ddz    }t        |      }dg|z  t        |      D ]&  }|   }t        j                  |d	            |<   ( d
 }dg|z  }t        |      D ]  }|   v r|||<   |ffd	}|||<     fd}| j                  |||      S t        d      r%t	              }| j                  t        |            S t        d      r| j                  t        g            S y)a  
        Return the centralizer of a group/set/element.

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

        The centralizer of a set of permutations ``S`` inside
        a group ``G`` is the set of elements of ``G`` that commute with all
        elements of ``S``::

            `C_G(S) = \{ g \in G | gs = sg \forall s \in S\}` ([10])

        Usually, ``S`` is a subset of ``G``, but if ``G`` is a proper subgroup of
        the full symmetric group, we allow for ``S`` to have elements outside
        ``G``.

        It is naturally a subgroup of ``G``; the centralizer of a permutation
        group is equal to the centralizer of any set of generators for that
        group, since any element commuting with the generators commutes with
        any product of the  generators.

        Parameters
        ==========

        other
            a permutation group/list of permutations/single permutation

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import (SymmetricGroup,
        ... CyclicGroup)
        >>> S = SymmetricGroup(6)
        >>> C = CyclicGroup(6)
        >>> H = S.centralizer(C)
        >>> H.is_subgroup(C)
        True

        See Also
        ========

        subgroup_search

        Notes
        =====

        The implementation is an application of ``.subgroup_search()`` with
        tests using a specific base for the group ``G``.

        ru   c                     t        |        S r*   r=   r   s    r/   r   z.PermutationGroup.centralizer.<locals>.<lambda>  s    s1vg rf   r   Nr   r   r7   Tpairsc                      yNTr   r  s    r/   r   z.PermutationGroup.centralizer.<locals>.<lambda>"      rf   c                     | |   }	|      }
|   }|j                   |      }|j                   |   }|   |      }||j                   |   k(  S r*   r   )computed_wordsr   rE   rep_orb_indexr   imim_reptr_elr   orbit_descr
orbit_repsr   s           r/   testz*PermutationGroup.centralizer.<locals>.test(  sp    *1-(3DG(<(7]]473!"s!3 ,] ;DG D
  "U%6%6v%>>>rf   c                     j                   D cg c]  }t        | |       c}j                   D cg c]  }t        ||        c}k(  S c c}w c c}w r*   )ru   r   )rE   r   rv   s     r/   propz*PermutationGroup.centralizer.<locals>.prop6  sI    050@0@AQA050@0@AS!AB BAAs
   AA)r   r   testsrj   
array_form)hasattr
is_trivialr5   r>   r8   r<   r   r=   sortschreier_sims_incrementalr   dictorbit_transversalsubgroup_searchr  r&   )rd   rv   r5   r   r   
num_orbits	long_baseorbit_reps_indicesrD   orbitpointr   r   r   j
rel_orbitsnum_rel_orbitsr   trivial_testr-  r   r*  r,  r   r   r(  r)  r   s    `                      @@@@r/   r  zPermutationGroup.centralizer  s   f 5,'4??[[FtE&M23H\\^FVJKK-K.I
*J"&
!2&-K:& .VAY %a
1(+I"1%" +E)*K&+%-	. !% > >I > ND+ 8{ KA3t9% $Q'H:5 8DH:& 1%2  !a%J _N 6.0L>* > m"&++Ct+<#>Q> *LF8OE8_ $7j(+E!H/0 ? ?  $E!H!$$B ''44?u ( N NUM*;D##$4T$:;;UL)##$4eW$=>> *rf   c                     |j                   }|j                   }g }|D ]/  }|D ](  }t        ||| |       }||vs|j                  |       * 1 | j                  |      }	|	S )a  
        Return the commutator of two subgroups.

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

        For a permutation group ``K`` and subgroups ``G``, ``H``, the
        commutator of ``G`` and ``H`` is defined as the group generated
        by all the commutators `[g, h] = hgh^{-1}g^{-1}` for ``g`` in ``G`` and
        ``h`` in ``H``. It is naturally a subgroup of ``K`` ([1], p.27).

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import (SymmetricGroup,
        ... AlternatingGroup)
        >>> S = SymmetricGroup(5)
        >>> A = AlternatingGroup(5)
        >>> G = S.commutator(S, A)
        >>> G.is_subgroup(A)
        True

        See Also
        ========

        derived_subgroup

        Notes
        =====

        The commutator of two subgroups `H, G` is equal to the normal closure
        of the commutators of all the generators, i.e. `hgh^{-1}g^{-1}` for `h`
        a generator of `H` and `g` a generator of `G` ([1], p.28)

        )ru   r   r   normal_closure)
rd   Gr   ggenshgenscommutatorsggenhgen
commutatorress
             r/   rG  zPermutationGroup.commutatorA  s{    H  	3D 3!$tedU;
[0&&z23	3
 !!+.
rf   c                    t        |t        t        f      r|j                         }t	        |      | j
                  k7  rt        d      t        t        | j
                              }| j                  }| j                  }g }| j                  }|}t        t	        |            D ]g  }	|||	      }
|
||	   k(  r|j                  |
       %|
||	   vrg c S ||	   |
   j                  }t        t        |      |      }|j                  |
       i ||k7  rg S |r|S | j                  }t        t	        |            D 	cg c]  }	||	   ||	       }}	|S c c}	w )a  Return ``G``'s (self's) coset factorization of ``g``

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

        If ``g`` is an element of ``G`` then it can be written as the product
        of permutations drawn from the Schreier-Sims coset decomposition,

        The permutations returned in ``f`` are those for which
        the product gives ``g``: ``g = f[n]*...f[1]*f[0]`` where ``n = len(B)``
        and ``B = G.base``. f[i] is one of the permutations in
        ``self._basic_orbits[i]``.

        If factor_index==True,
        returns a tuple ``[b[0],..,b[n]]``, where ``b[i]``
        belongs to ``self._basic_orbits[i]``

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation(0, 1, 3, 7, 6, 4)(2, 5)
        >>> b = Permutation(0, 1, 3, 2)(4, 5, 7, 6)
        >>> G = PermutationGroup([a, b])

        Define g:

        >>> g = Permutation(7)(1, 2, 4)(3, 6, 5)

        Confirm that it is an element of G:

        >>> G.contains(g)
        True

        Thus, it can be written as a product of factors (up to
        3) drawn from u. See below that a factor from u1 and u2
        and the Identity permutation have been used:

        >>> f = G.coset_factor(g)
        >>> f[2]*f[1]*f[0] == g
        True
        >>> f1 = G.coset_factor(g, True); f1
        [0, 4, 4]
        >>> tr = G.basic_transversals
        >>> f[0] == tr[0][f1[0]]
        True

        If g is not an element of G then [] is returned:

        >>> c = Permutation(5, 6, 7)
        >>> G.coset_factor(c)
        []

        See Also
        ========

        sympy.combinatorics.util._strip

        z.g should be the same size as permutations of G)r+   r   r   r8   r=   rZ   r   r<   r   r_   r   r   r   r   r
   r   )rd   rE   factor_indexIr   r   factorsr   r   rD   r  r  trs                r/   coset_factorzPermutationGroup.coset_factorp  sN   x a%-.Aq6T\\! MNNt||$%(())yys4y! 		!AT!W:DtAwt$<?*	Q%11AA*ANN4 		! 6IN$$.3CI.>?2a5$?? @s   ;Ec                 8   g }|j                   rg S || j                  v rN|r|| j                  v r|gS | j                  |   }|D ]%  } |j                  | j                  |d             ' |S |dz  | j                  v r|dz  }|r|| j                  v r|dz  gS | j                  |   }|D ]%  } |j                  | j                  |d             ' t        |      }t        |      D cg c]  }|||z
  dz
     dz   }}|S | j                  |d      }t        |      D ]r  \  }}	| j                  |   |	   }|D ]V  }|s  |j                  | j                  |          %| j                  |   } |j                  | j                  |d             X t |S c c}w )z
        Return a list of strong generators `[s1, \dots, sn]`
        s.t `g = sn \times \dots \times s1`. If ``original=True``, make the
        list contain only the original group generators

        Toriginalr   r7   )r?   r   ru   r]   r   generator_productr=   r<   rN  r   r`   r   )
rd   rE   rQ  r   slpsr   rD   fr;  s
             r/   rR  z"PermutationGroup.generator_product  s    ==I   qDOO3s
++A. MA"GNN4#9#9!d#9#KLMUd&&&2AqDOO32w++A. MA"GNN4#9#9!d#9#KLML7<Qx@!71Q3q5>2-@@a&aL 	MDAq''*1-C M"GNN4#3#3A#67((+A"GNN4#9#9!d#9#KLM	M  As   *Fc                    | j                  |d      }|syd}d}| j                  }| j                  }| j                  }t	        t        |            D ]4  }||   }	||   j                  |	      }
|||
z  z  }|t        ||         z  }6 |S )a;  rank using Schreier-Sims representation.

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

        The coset rank of ``g`` is the ordering number in which
        it appears in the lexicographic listing according to the
        coset decomposition

        The ordering is the same as in G.generate(method='coset').
        If ``g`` does not belong to the group it returns None.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation(0, 1, 3, 7, 6, 4)(2, 5)
        >>> b = Permutation(0, 1, 3, 2)(4, 5, 7, 6)
        >>> G = PermutationGroup([a, b])
        >>> c = Permutation(7)(2, 4)(3, 5)
        >>> G.coset_rank(c)
        16
        >>> G.coset_unrank(16)
        (7)(2 4)(3 5)

        See Also
        ========

        coset_factor

        TNr   r7   )rN  r_   r[   r^   r<   r=   r   )rd   rE   rL  rankr   r   r   r   rD   r   r;  s              r/   
coset_rankzPermutationGroup.coset_rank  s    @ ##At,))zz))s4y! 	'A
AQ%%a(AAaCKD#l1o&&A		'
 rf   c                    |dk  s|| j                         k\  ry| j                  }| j                  }| j                  }t	        |      }dg|z  }t        |      D ](  }t        |t	        ||               \  }}	||   |	   ||<   * t        |      D cg c]  }||   ||      j                   }
}t        |
 }|r|S t        |      S c c}w )zunrank using Schreier-Sims representation

        coset_unrank is the inverse operation of coset_rank
        if 0 <= rank < order; otherwise it returns None.

        r   N)
r   r   r   r   r=   r<   divmodr   r   r>   )rd   rW  afr   r   r   mvrD   cr.   r   s               r/   coset_unrankzPermutationGroup.coset_unrank#  s     !8ttzz|+yy..((ICEq 	&AT3|A#78GD!?1%AaD	& 9>aA1\!_QqT"..AAqMH1: Bs   Cc                     | j                   S )a  Returns the size of the permutations in the group.

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

        The number of permutations comprising the group is given by
        ``len(group)``; the number of permutations that can be generated
        by the group is given by ``group.order()``.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation([1, 0, 2])
        >>> G = PermutationGroup([a])
        >>> G.degree
        3
        >>> len(G)
        1
        >>> G.order()
        2
        >>> list(G.generate())
        [(2), (2)(0 1)]

        See Also
        ========

        order
        )rZ   rq   s    r/   r5   zPermutationGroup.degree;  s    > ||rf   c                 P    t        t        t        | j                                    S )zH
        Return the identity element of the permutation group.

        )r>   r8   r<   r5   rq   s    r/   r   zPermutationGroup.identity\  s     tE$++./00rf   c                 n    | j                   st        | j                               | _         | j                   S )aI  Returns all the elements of the permutation group as a list

        Examples
        ========

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

        )rJ   r8   generaterq   s    r/   r   zPermutationGroup.elementsd  s'     ~~!$--/2DN~~rf   c                     | g}| }| j                         }|j                  |      s5|j                  |       |}|j                         }|j                  |      s5|S )aI  Return the derived series for the group.

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

        The derived series for a group `G` is defined as
        `G = G_0 > G_1 > G_2 > \ldots` where `G_i = [G_{i-1}, G_{i-1}]`,
        i.e. `G_i` is the derived subgroup of `G_{i-1}`, for
        `i\in\mathbb{N}`. When we have `G_k = G_{k-1}` for some
        `k\in\mathbb{N}`, the series terminates.

        Returns
        =======

        A list of permutation groups containing the members of the derived
        series in the order `G = G_0, G_1, G_2, \ldots`.

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import (SymmetricGroup,
        ... AlternatingGroup, DihedralGroup)
        >>> A = AlternatingGroup(5)
        >>> len(A.derived_series())
        1
        >>> S = SymmetricGroup(4)
        >>> len(S.derived_series())
        4
        >>> S.derived_series()[1].is_subgroup(AlternatingGroup(4))
        True
        >>> S.derived_series()[2].is_subgroup(DihedralGroup(2))
        True

        See Also
        ========

        derived_subgroup

        )derived_subgroupr   r   rd   rH  currentnxts       r/   r   zPermutationGroup.derived_seriesv  sb    P f##%%%c*JJsOG&&(C %%c* 
rf   c                    | j                   }| j                  D cg c]  }|j                   }}t               }| j                  }t        t        |            }t        |      D ]i  }t        |      D ]Y  }||   }	||   }
t        t        |            }|D ]  }|	|
|      ||
|	|      <    t        |      }||vsI|j                  |       [ k |D cg c]  }t        |       }}| j                  |      }|S c c}w c c}w )a  Compute the derived subgroup.

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

        The derived subgroup, or commutator subgroup is the subgroup generated
        by all commutators `[g, h] = hgh^{-1}g^{-1}` for `g, h\in G` ; it is
        equal to the normal closure of the set of commutators of the generators
        ([1], p.28, [11]).

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation([1, 0, 2, 4, 3])
        >>> b = Permutation([0, 1, 3, 2, 4])
        >>> G = PermutationGroup([a, b])
        >>> C = G.derived_subgroup()
        >>> list(C.generate(af=True))
        [[0, 1, 2, 3, 4], [0, 1, 3, 4, 2], [0, 1, 4, 2, 3]]

        See Also
        ========

        derived_series

        )rY   ru   r   rt   rZ   r8   r<   tupleaddr>   r@  )rd   r   r   r   set_commutatorsr5   rngrD   r;  p1p2r^  r   ctcmsG2s                   r/   re  z!PermutationGroup.derived_subgroup  s   8 GG'+7!77%5=!q 		,A1X ,!W!Wv' -A#%be9AbAiL-1X_,#''+,		, $33awqz33  %	! 8 4s   C<Dc                 v    |dk(  r| j                  |      S |dk(  r| j                  |      S t        d|z        )a  Return iterator to generate the elements of the group.

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

        Iteration is done with one of these methods::

          method='coset'  using the Schreier-Sims coset representation
          method='dimino' using the Dimino method

        If ``af = True`` it yields the array form of the permutations

        Examples
        ========

        >>> from sympy.combinatorics import PermutationGroup
        >>> from sympy.combinatorics.polyhedron import tetrahedron

        The permutation group given in the tetrahedron object is also
        true groups:

        >>> G = tetrahedron.pgroup
        >>> G.is_group
        True

        Also the group generated by the permutations in the tetrahedron
        pgroup -- even the first two -- is a proper group:

        >>> H = PermutationGroup(G[0], G[1])
        >>> J = PermutationGroup(list(H.generate())); J
        PermutationGroup([
            (0 1)(2 3),
            (1 2 3),
            (1 3 2),
            (0 3 1),
            (0 2 3),
            (0 3)(1 2),
            (0 1 3),
            (3)(0 2 1),
            (0 3 2),
            (3)(0 1 2),
            (0 2)(1 3)])
        >>> _.is_group
        True
        cosetdiminozNo generation defined for %s)generate_schreier_simsgenerate_diminor   )rd   methodr[  s      r/   rc  zPermutationGroup.generate  sH    \ W..r22x''++%&Dv&MNNrf   c           	   #     K   t        t        | j                              }d}|g}t        |      h}|r| nt	        |       | j
                  D cg c]  }|j                   }}t        t        |            D ]  }|dd }	|g}
|
s|
}g }
|D ]  }|d|dz    D ]  }t        ||      }t        |      |vs|	D ]e  }|dz  }t        ||      }|r| nt	        |      }| |j                  |       |j                  t        |             |
j                  |       g   |
r t        |      | _        yc c}w w)a  Yield group elements using Dimino's algorithm.

        If ``af == True`` it yields the array form of the permutations.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation([0, 2, 1, 3])
        >>> b = Permutation([0, 2, 3, 1])
        >>> g = PermutationGroup([a, b])
        >>> list(g.generate_dimino(af=True))
        [[0, 1, 2, 3], [0, 2, 1, 3], [0, 2, 3, 1],
         [0, 1, 3, 2], [0, 3, 2, 1], [0, 3, 1, 2]]

        References
        ==========

        .. [1] The Implementation of Various Algorithms for Permutation Groups in
               the Computer Algebra System: AXIOM, N.J. Doye, M.Sc. Thesis

        r   Nr7   )r8   r<   r5   rj  r>   ru   r   r=   r   r   rk  rI   )rd   r[  idnr   element_listset_element_listr   r   rD   DNr  r.   rE   agdaps                    r/   rw  z PermutationGroup.generate_dimino  sQ    . 5%&u!#J<I#,'+7!77s4y! 	-AQAA -A!&1q5\ -%a^ 9,<<%& 
- %
%-a_#%*,H(/A*+G , 3 3B 7 0 4 4U2Y ? !
-	-- 		-. ,'3 8s%   AED='#E-E9A0E*Ec              #     K   | j                   }| j                  }| j                  }t        |      dk(  r'| j                  D ]  }|r|j
                   |  yt        |      dk(  r,|d   D ]#  }|r|d   |   j
                   |d   |    % yt        t        |            }|ddd   }t        t        |            g}|D cg c]  }t        |       }}t        |      dz
  }	dg|	z  }
d}	 |
|   ||   k\  r!|dk(  ryd|
|<   |dz  }|j                          -t        ||   ||   |
|         j
                  |d         }|
|xx   dz  cc<   |j                  |       |dz  }||	k(  r}|r.|d   D ]%  }t        |d   |   j
                  |d         }| ' n8|d   D ]0  }t        |d   |   j
                  |d         }t        |      }| 2 |j                          |dz  }c c}w w)a,  Yield group elements using the Schreier-Sims representation
        in coset_rank order

        If ``af = True`` it yields the array form of the permutations

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation([0, 2, 1, 3])
        >>> b = Permutation([0, 2, 3, 1])
        >>> g = PermutationGroup([a, b])
        >>> list(g.generate_schreier_sims(af=True))
        [[0, 1, 2, 3], [0, 2, 1, 3], [0, 3, 2, 1],
         [0, 1, 3, 2], [0, 2, 3, 1], [0, 3, 1, 2]]
        r   Nr7   r   )rZ   r   r^   r=   ru   r   r8   reversedr<   r:   r   r   r>   )rd   r[  r   r  r   r   rD   stgposmaxr   r   r   r   rn  s                 r/   rv  z'PermutationGroup.generate_schreier_simsE  s,    $ LL##))q6Q;__ --'G	
 q6Q;!!_ "A$q'---A$q'M	"
 !#DbD)E!H~"#$Q#a&$$[1_c"f1v"6AQ	1l1oc!f56BBCGLAFaKFJJqMFABw)"-  $QrU1X%9%93r7C  *"- !$QrU1X%9%93r7C$QZ ! 	Q1 	 %s   C	G5G0DG5c                     | j                   S )aF  Returns the generators of the group.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation([0, 2, 1])
        >>> b = Permutation([1, 0, 2])
        >>> G = PermutationGroup([a, b])
        >>> G.generators
        [(1 2), (2)(0 1)]

        rh   rq   s    r/   ru   zPermutationGroup.generators  s     rf   c                     t        |t              sy|j                  | j                  k7  r|ryt        || j                        }|| j                  v ryt        | j                  |j                  d            S )a  Test if permutation ``g`` belong to self, ``G``.

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

        If ``g`` is an element of ``G`` it can be written as a product
        of factors drawn from the cosets of ``G``'s stabilizers. To see
        if ``g`` is one of the actual generators defining the group use
        ``G.has(g)``.

        If ``strict`` is not ``True``, ``g`` will be resized, if necessary,
        to match the size of permutations in ``self``.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup

        >>> a = Permutation(1, 2)
        >>> b = Permutation(2, 3, 1)
        >>> G = PermutationGroup(a, b, degree=5)
        >>> G.contains(G[0]) # trivial check
        True
        >>> elem = Permutation([[2, 3]], size=5)
        >>> G.contains(elem)
        True
        >>> G.contains(Permutation(4)(0, 1, 2, 3))
        False

        If strict is False, a permutation will be resized, if
        necessary:

        >>> H = PermutationGroup(Permutation(5))
        >>> H.contains(Permutation(3))
        False
        >>> H.contains(Permutation(3), strict=False)
        True

        To test if a given permutation is present in the group:

        >>> elem in G.generators
        False
        >>> G.has(elem)
        False

        See Also
        ========

        coset_factor, sympy.core.basic.Basic.has, __contains__

        Fr2   T)r+   r   r3   r5   ru   boolrN  r.  )rd   rE   stricts      r/   rn   zPermutationGroup.contains  sc    h ![)66T[[ ADKK0AD%%allD9::rf   c                 z    | j                   $| j                  | j                               | _         | j                   S )a  Return ``True`` if the group is perfect.
        A group is perfect if it equals to its derived subgroup.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation(1,2,3)(4,5)
        >>> b = Permutation(1,2,3,4,5)
        >>> G = PermutationGroup([a, b])
        >>> G.is_perfect
        False

        )rV   r{   re  rq   s    r/   
is_perfectzPermutationGroup.is_perfect  s6      ##{{4+@+@+BCDrf   c                     | j                   | j                   S d| _         | j                  D cg c]  }|j                   }}|D ]%  }|D ]  }||k  r	t        ||      rd| _           y ' yc c}w )a  Test if the group is Abelian.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation([0, 2, 1])
        >>> b = Permutation([1, 0, 2])
        >>> G = PermutationGroup([a, b])
        >>> G.is_abelian
        False
        >>> a = Permutation([0, 2, 1])
        >>> G = PermutationGroup([a])
        >>> G.is_abelian
        True

        TF)rL   ru   r   r	   )rd   r   r   r   r   s        r/   
is_abelianzPermutationGroup.is_abelian  s    & '###'+7!77 	!A !6(A.',D$ !	!  8s   A.c                 n   | j                   rg S | j                  }g }| }|j                         }|j                  }t        |j	                               D ]  }g }	 g }|D ]*  }	|	|z  }
|j                  |
      r|j                  |
       , |rt        ||z         n|}|j	                         |j	                         z  }|}|}|dk(  rn|j                  t        ||             |sdg|d   z  }|D ]  }t        |      D ]  }||   |z  ||<     |j                  |        |j                          |S )aF  
        Returns the abelian invariants for the given group.
        Let ``G`` be a nontrivial finite abelian group. Then G is isomorphic to
        the direct product of finitely many nontrivial cyclic groups of
        prime-power order.

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

        The prime-powers that occur as the orders of the factors are uniquely
        determined by G. More precisely, the primes that occur in the orders of the
        factors in any such decomposition of ``G`` are exactly the primes that divide
        ``|G|`` and for any such prime ``p``, if the orders of the factors that are
        p-groups in one such decomposition of ``G`` are ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``,
        then the orders of the factors that are p-groups in any such decomposition of ``G``
        are ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``.

        The uniquely determined integers ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``, taken
        for all primes that divide ``|G|`` are called the invariants of the nontrivial
        group ``G`` as suggested in ([14], p. 542).

        Notes
        =====

        We adopt the convention that the invariants of a trivial group are [].

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation([0, 2, 1])
        >>> b = Permutation([1, 0, 2])
        >>> G = PermutationGroup([a, b])
        >>> G.abelian_invariants()
        [2]
        >>> from sympy.combinatorics import CyclicGroup
        >>> G = CyclicGroup(7)
        >>> G.abelian_invariants()
        [7]

        r7   r   )r0  ru   re  r   r   rn   r   r&   r    r<   r   r1  )rd   gnsinvrA  r   Hgensr   r   powsrE   elmr   r   rD   r;  s                  r/   abelian_invariantsz#PermutationGroup.abelian_invariants  sM   T ??Ioo aggi( 	!AE )AQ$C::c?C() 7;$UT\2GGIqwwy(6\!Q/0  s58| ,A"1X ,"&q'!)Q,, 

4 +	!, 	

rf   c                 \    | j                   xr t        fd| j                  D              S )a  Return ``True`` if the group is elementary abelian. An elementary
        abelian group is a finite abelian group, where every nontrivial
        element has order `p`, where `p` is a prime.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation([0, 2, 1])
        >>> G = PermutationGroup([a])
        >>> G.is_elementary(2)
        True
        >>> a = Permutation([0, 2, 1, 3])
        >>> b = Permutation([3, 1, 2, 0])
        >>> G = PermutationGroup([a, b])
        >>> G.is_elementary(2)
        True
        >>> G.is_elementary(3)
        False

        c              3   D   K   | ]  }|j                         k(    y wr*   r   )r-   rE   r   s     r/   r0   z1PermutationGroup.is_elementary.<locals>.<genexpr>o  s     &O!qwwyA~&O    )r  r   ru   )rd   r   s    `r/   is_elementaryzPermutationGroup.is_elementaryY  s#    , O3&Ot&O#OOrf   c                     |r|rt        dj                  ||            | j                  }t        |      }| j	                         }||k(  rd| _        d| _        |ryyd|z  |k(  rd| _        d| _        |ryyy)z#A naive test using the group order.z$Both {} and {} cannot be set to TrueTFr   )r   formatr5   
_factorialr   rN   rO   )rd   only_symonly_altr   	sym_orderr   s         r/   _eval_is_alt_sym_naivez'PermutationGroup._eval_is_alt_sym_naiveq  s    6(+- - KKqM	

IDL DLuW	! DLDLrf   c                     |n j                   }|dk  rd}nd}|t        d      z  t        |      z  }t        t        |       |z        } fdt        |      D        } j	                  |      S |D ]  }t        |      s y y)	a  A test using monte-carlo algorithm.

        Parameters
        ==========

        eps : float, optional
            The criterion for the incorrect ``False`` return.

        perms : list[Permutation], optional
            If explicitly given, it tests over the given candidates
            for testing.

            If ``None``, it randomly computes ``N_eps`` and chooses
            ``N_eps`` sample of the permutation from the group.

        See Also
        ========

        _check_cycles_alt_sym
           g(\?g=
ףp=?r   c              3   >   K   | ]  }j                           y wr*   )r   )r-   rD   rd   s     r/   r0   z@PermutationGroup._eval_is_alt_sym_monte_carlo.<locals>.<genexpr>  s     <!T^^%<s   permsTF)r5   r   intr<   _eval_is_alt_sym_monte_carlor   )rd   epsr  r   c_nd_nN_epsr   s   `       r/   r  z-PermutationGroup._eval_is_alt_sym_monte_carlo  s    * =A2vs1v:s1v%CS	#&E<uU|<E4454AA 	D$T*	 rf   c                 p   +d   }fdt        |      D        }| j                  |      S | j                  s| j                  ry| j                  du r| j                  du ry| j                  }|dk  r| j                         S | j                         r| j                  |      S d\  | _        | _        y)	aU  Monte Carlo test for the symmetric/alternating group for degrees
        >= 8.

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

        More specifically, it is one-sided Monte Carlo with the
        answer True (i.e., G is symmetric/alternating) guaranteed to be
        correct, and the answer False being incorrect with probability eps.

        For degree < 8, the order of the group is checked so the test
        is deterministic.

        Notes
        =====

        The algorithm itself uses some nontrivial results from group theory and
        number theory:
        1) If a transitive group ``G`` of degree ``n`` contains an element
        with a cycle of length ``n/2 < p < n-2`` for ``p`` a prime, ``G`` is the
        symmetric or alternating group ([1], pp. 81-82)
        2) The proportion of elements in the symmetric/alternating group having
        the property described in 1) is approximately `\log(2)/\log(n)`
        ([1], p.82; [2], pp. 226-227).
        The helper function ``_check_cycles_alt_sym`` is used to
        go over the cycles in a permutation and look for ones satisfying 1).

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import DihedralGroup
        >>> D = DihedralGroup(10)
        >>> D.is_alt_sym()
        False

        See Also
        ========

        _check_cycles_alt_sym

        r  c              3   (   K   | ]	  }|     y wr*   r   )r-   rD   r   s     r/   r0   z.PermutationGroup.is_alt_sym.<locals>.<genexpr>  s     :LO:   r  TF   )r  FF)r<   r  rN   rO   r5   r  is_transitive)rd   r  r   r  r  r   s     `   r/   
is_alt_symzPermutationGroup.is_alt_sym  s    T # )E:U5\:E4454AA<<4<<<<5 T\\U%:KKq5..00!444==%1"dlrf   c                 6   | j                   | j                         }|t        |      dz
     }|j                  }| j                  }t        t        t        |                  t        fd|D              rd| _	        d| _         yd| _         y| j                   S )a  Test if the group is nilpotent.

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

        A group `G` is nilpotent if it has a central series of finite length.
        Alternatively, `G` is nilpotent if its lower central series terminates
        with the trivial group. Every nilpotent group is also solvable
        ([1], p.29, [12]).

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import (SymmetricGroup,
        ... CyclicGroup)
        >>> C = CyclicGroup(6)
        >>> C.is_nilpotent
        True
        >>> S = SymmetricGroup(5)
        >>> S.is_nilpotent
        False

        See Also
        ========

        lower_central_series, is_solvable

        r7   c              3   (   K   | ]	  }|k(    y wr*   r   r-   rE   r   s     r/   r0   z0PermutationGroup.is_nilpotent.<locals>.<genexpr>       /Q1=/r  TF)
rQ   lower_central_seriesr=   ru   r5   r>   r8   r<   r   rR   )rd   lcs
terminatorr   r5   r   s        @r/   is_nilpotentzPermutationGroup.is_nilpotent  s    < %++-CSX\*J((D[[FtE&M23H/$//$(!%)"%*"%%%rf   c           	      ~   | j                  ||      sy| j                  }|j                  }| j                  r||k(  s|sy| j                  ry| j	                         }|sU||k7  rP||k  r&t        |j                  t        |dz
        gz         }n%t        |j                  t        |dz
        gz         }|j                  D cg c]  }|j                   }}|j                  D cg c]  }|j                   }}|D ]4  }	|D ]-  }
t        |	|
t        |	            }|j                  |d      r,  y 6 yc c}w c c}w )az  Test if ``G=self`` is a normal subgroup of ``gr``.

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

        G is normal in gr if
        for each g2 in G, g1 in gr, ``g = g1*g2*g1**-1`` belongs to G
        It is sufficient to check this for each g1 in gr.generators and
        g2 in G.generators.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation([1, 2, 0])
        >>> b = Permutation([1, 0, 2])
        >>> G = PermutationGroup([a, b])
        >>> G1 = PermutationGroup([a, Permutation([2, 0, 1])])
        >>> G1.is_normal(G)
        True

        r  FTr7   )r   r5   r0  rL   copy	PermGroupru   r   r   r   r
   rN  )rd   grr  d_selfd_grnew_selfr   r   r   g1g2s              r/   	is_normalzPermutationGroup.is_normal  s-   . 62yy??$f99;&D.}$X%8%8Kq<Q;R%RSr}}FQJ0G/HHI(0(;(;<1<<(*6166 	!B !b"jn5,,Q5 !	!
  =6s   D5&D:c                    | j                   | j                   S | j                         du ry|rYg }| j                  d      }t        t	        |             D ]#  }|j                  | j                  d|             % t        |      }n| j                  d      }|j                         }|D ]D  }|j                         }|dk7  st        d | j                  d|g      D              s=d| _          y d| _         y)aS  Test if a group is primitive.

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

        A permutation group ``G`` acting on a set ``S`` is called primitive if
        ``S`` contains no nontrivial block under the action of ``G``
        (a block is nontrivial if its cardinality is more than ``1``).

        Notes
        =====

        The algorithm is described in [1], p.83, and uses the function
        minimal_block to search for blocks of the form `\{0, k\}` for ``k``
        ranging over representatives for the orbits of `G_0`, the stabilizer of
        ``0``. This algorithm has complexity `O(n^2)` where ``n`` is the degree
        of the group, and will perform badly if `G_0` is small.

        There are two implementations offered: one finds `G_0`
        deterministically using the function ``stabilizer``, and the other
        (default) produces random elements of `G_0` using ``random_stab``,
        hoping that they generate a subgroup of `G_0` with not too many more
        orbits than `G_0` (this is suggested in [1], p.83). Behavior is changed
        by the ``randomized`` flag.

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import DihedralGroup
        >>> D = DihedralGroup(10)
        >>> D.is_primitive()
        False

        See Also
        ========

        minimal_block, random_stab

        Fr   c              3   &   K   | ]	  }|d k7    ywr   Nr   r-   r   s     r/   r0   z0PermutationGroup.is_primitive.<locals>.<genexpr>  s     Ia1fI   T)rP   r  r   r<   r=   r   r   r&   
stabilizerr   r:   r9   minimal_block)	rd   r   random_stab_gensr]  r   stabr   orbr   s	            r/   is_primitivezPermutationGroup.is_primitiveK  s    P )%%%5(!$$Q'A3t9% @ ''(8(8A(>?@#$45D??1%D 	C	AAv#Id.@.@!Q.HII%*"		
 "rf   c                 z   d }| j                         syg }g }g }|rYg }| j                  d      }t        t        |             D ]#  }|j	                  | j                  d|             % t        |      }	n| j                  d      }	|	j                         }
|
D ]  }|j                         }|dk7  s| j                  d|g      } ||      \  }}t        | j                        D ch c]  }||   dk(  s| }}d}dgt        |      z  }t        |      D ]`  \  }}t        |      t        |      kD  r|j                  |      rd||<   4t        |      t        |      k  sL|j                  |      s^d} n t        |      D cg c]  \  }}||   r| }}}t        |      D cg c]  \  }}||   r| }}}t        |      D cg c]  \  }}||   r| }}}|sO||vsU|j	                  |       |j	                  |       |j	                  |        |S c c}w c c}}w c c}}w c c}}w )aX  
        For a transitive group, return the list of all minimal
        block systems. If a group is intransitive, return `False`.

        Examples
        ========
        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> from sympy.combinatorics.named_groups import DihedralGroup
        >>> DihedralGroup(6).minimal_blocks()
        [[0, 1, 0, 1, 0, 1], [0, 1, 2, 0, 1, 2]]
        >>> G = PermutationGroup(Permutation(1,2,5))
        >>> G.minimal_blocks()
        False

        See Also
        ========

        minimal_block, is_transitive, is_primitive

        c                     t        |       }i }d}d g|z  }t        |      D ]'  }| |   |vr||| |   <   |||<   |dz  }|| |      ||<   ) t        |      |fS )Nr   r7   )r=   r<   rj  )blocksr   appearedr\  r   rD   s         r/   _number_blocksz7PermutationGroup.minimal_blocks.<locals>._number_blocks  s    
 FAHAqA1X /!9H,*+HVAY'AaDFA#F1I.AaD/ 8Q;rf   Fr   T)r  r   r<   r=   r   r   r&   r  r   r:   r  r5   r   issubset)rd   r   r  r  
num_blocks
rep_blocksr  r]  rD   r  r   r  r   block	num_blockr   r;  r   minimalblocks_remove_maskr   r   r   s                          r/   minimal_blockszPermutationGroup.minimal_blocks  s6   *	$ !!#

!$$Q'A3t9% @ ''(8(8A(>?@#$45D??1%D 	+C	AAv**Aq62-e4	1"'"4JQ	!8IqJJ &+Ws6{%:"%j1 DAq1vC(S\\!_04*1-Q#c(*qzz#"' )2&(9W1ASTUAV!WW,5j,A_DAqI[\]I^a_
_,5j,A_DAqI[\]I^a_
_y
:MM%(%%i0%%c*7	+8 - K X__s0   (H&6H&	H+H+,H1:H1H7H7c                 V   | j                   | j                         dz  dk7  ry| j                         }|t        |      dz
     }|j                  }| j
                  }t        t        t        |                  t        fd|D              rd| _         yd| _         y| j                   S )a  Test if the group is solvable.

        ``G`` is solvable if its derived series terminates with the trivial
        group ([1], p.29).

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import SymmetricGroup
        >>> S = SymmetricGroup(3)
        >>> S.is_solvable
        True

        See Also
        ========

        is_nilpotent, derived_series

        r   r   Tr7   c              3   (   K   | ]	  }|k(    y wr*   r   r  s     r/   r0   z/PermutationGroup.is_solvable.<locals>.<genexpr>  r  r  F)
rR   r   r   r=   ru   r5   r>   r8   r<   r   )rd   dsr  r   r5   r   s        @r/   is_solvablezPermutationGroup.is_solvable  s    * $zz|a1$$$&BCGaKJ((D[[FtE&M23H/$//$(!$)!$$$rf   c                    t        t              r| j                  j                  k7  ryyt        t              sy| k(  s| j                  d   t               k(  ryj                         | j                         z  dk7  ry| j                  j                  k(  s| j                  j                  k  rs| j                  }nyt        fd|D              S )aN  Return ``True`` if all elements of ``self`` belong to ``G``.

        If ``strict`` is ``False`` then if ``self``'s degree is smaller
        than ``G``'s, the elements will be resized to have the same degree.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> from sympy.combinatorics import SymmetricGroup, CyclicGroup

        Testing is strict by default: the degree of each group must be the
        same:

        >>> p = Permutation(0, 1, 2, 3, 4, 5)
        >>> G1 = PermutationGroup([Permutation(0, 1, 2), Permutation(0, 1)])
        >>> G2 = PermutationGroup([Permutation(0, 2), Permutation(0, 1, 2)])
        >>> G3 = PermutationGroup([p, p**2])
        >>> assert G1.order() == G2.order() == G3.order() == 6
        >>> G1.is_subgroup(G2)
        True
        >>> G1.is_subgroup(G3)
        False
        >>> G3.is_subgroup(PermutationGroup(G3[1]))
        False
        >>> G3.is_subgroup(PermutationGroup(G3[0]))
        True

        To ignore the size, set ``strict`` to ``False``:

        >>> S3 = SymmetricGroup(3)
        >>> S5 = SymmetricGroup(5)
        >>> S3.is_subgroup(S5, strict=False)
        True
        >>> C7 = CyclicGroup(7)
        >>> G = S5*C7
        >>> S5.is_subgroup(G, False)
        True
        >>> C7.is_subgroup(G, 0)
        False

        FTr   c              3   D   K   | ]  }j                  |         yw)r  N)rn   )r-   rE   rA  r  s     r/   r0   z/PermutationGroup.is_subgroup.<locals>.<genexpr>=	  s     >A1::a:/>r  )r+   SymmetricPermutationGroupr5   r&   ru   r   r   r   )rd   rA  r  r   s    `` r/   r   zPermutationGroup.is_subgroup	  s    V a23{{ahh&!-.19*KM9779tzz|#q(;;!(("qxx'??D>>>>rf   c                     | j                   S )a  Return ``True`` if a group is polycyclic. A group is polycyclic if
        it has a subnormal series with cyclic factors. For finite groups,
        this is the same as if the group is solvable.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation([0, 2, 1, 3])
        >>> b = Permutation([2, 0, 1, 3])
        >>> G = PermutationGroup([a, b])
        >>> G.is_polycyclic
        True

        )r  rq   s    r/   is_polycycliczPermutationGroup.is_polycyclic?	  s    " rf   c                 "   | j                   r| j                   S |rH| j                   | j                   S t        | j                  d            | j                  k(  }|| _         |S d}| j	                         D ]  }t        |      dkD  s|r yd} |S )a  Test if the group is transitive.

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

        A group is transitive if it has a single orbit.

        If ``strict`` is ``False`` the group is transitive if it has
        a single orbit of length different from 1.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation([0, 2, 1, 3])
        >>> b = Permutation([2, 0, 1, 3])
        >>> G1 = PermutationGroup([a, b])
        >>> G1.is_transitive()
        False
        >>> G1.is_transitive(strict=False)
        True
        >>> c = Permutation([2, 3, 0, 1])
        >>> G2 = PermutationGroup([a, c])
        >>> G2.is_transitive()
        True
        >>> d = Permutation([1, 0, 2, 3])
        >>> e = Permutation([0, 1, 3, 2])
        >>> G3 = PermutationGroup([d, e])
        >>> G3.is_transitive() or G3.is_transitive(strict=False)
        False

        r   Fr7   T)rM   r=   r9  r5   r   )rd   r  ansgot_orbr   s        r/   r  zPermutationGroup.is_transitiveR	  s    B &&&"".***djjm$3C"%DJ 	A1vz 		
 rf   c                 z    | j                   $t        |       dk(  xr | d   j                  | _         | j                   S )aK  Test if the group is the trivial group.

        This is true if the group contains only the identity permutation.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> G = PermutationGroup([Permutation([0, 1, 2])])
        >>> G.is_trivial
        True

        r7   r   )rS   r=   is_Identityrq   s    r/   r0  zPermutationGroup.is_trivial	  s;     #"4yA~E$q'2E2EDrf   c                     | g}| }| j                  | |      }|j                  |      s7|j                  |       |}| j                  | |      }|j                  |      s7|S )a%  Return the lower central series for the group.

        The lower central series for a group `G` is the series
        `G = G_0 > G_1 > G_2 > \ldots` where
        `G_k = [G, G_{k-1}]`, i.e. every term after the first is equal to the
        commutator of `G` and the previous term in `G1` ([1], p.29).

        Returns
        =======

        A list of permutation groups in the order `G = G_0, G_1, G_2, \ldots`

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import (AlternatingGroup,
        ... DihedralGroup)
        >>> A = AlternatingGroup(4)
        >>> len(A.lower_central_series())
        2
        >>> A.lower_central_series()[1].is_subgroup(DihedralGroup(2))
        True

        See Also
        ========

        commutator, derived_series

        )rG  r   r   rf  s       r/   r  z%PermutationGroup.lower_central_series	  se    < foodG,%%c*JJsOG//$0C %%c* 
rf   c                     | j                   | j                   S | j                  }|dk(  ryt        D ]  }||z  dk(  s||z  }|| _         |c S  y)a  Maximum proper divisor of the degree of a permutation group.

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

        Obviously, this is the degree divided by its minimal proper divisor
        (larger than ``1``, if one exists). As it is guaranteed to be prime,
        the ``sieve`` from ``sympy.ntheory`` is used.
        This function is also used as an optimization tool for the functions
        ``minimal_block`` and ``_union_find_merge``.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> G = PermutationGroup([Permutation([0, 2, 1, 3])])
        >>> G.max_div
        2

        See Also
        ========

        minimal_block, _union_find_merge

        Nr7   r   )rU   r5   r   )rd   r   r   r  s       r/   r   zPermutationGroup.max_div	  sZ    6 ==$== KK6 	A1uzqD !		rf   c                    | j                         sy| j                  }| j                  }t        t	        |            }dg|z  }g }t        |      }|| j                  kD  rdg|z  S t	        |dz
        D ]'  }|d   |||dz      <   |j                  ||dz             ) |||d   <   d}|dz
  }	||	k  r\||   }
|dz  }|D ]G  }| j                  |
|      }| j                   ||
       ||      |||      }|dk(  rdg|z  c S |	|z  }	I ||	k  r\t	        |      D ]  }| j                  ||        i }t        |      D cg c]  \  }}|j                  ||       c}}S c c}}w )a  For a transitive group, finds the block system generated by
        ``points``.

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

        If a group ``G`` acts on a set ``S``, a nonempty subset ``B`` of ``S``
        is called a block under the action of ``G`` if for all ``g`` in ``G``
        we have ``gB = B`` (``g`` fixes ``B``) or ``gB`` and ``B`` have no
        common points (``g`` moves ``B`` entirely). ([1], p.23; [6]).

        The distinct translates ``gB`` of a block ``B`` for ``g`` in ``G``
        partition the set ``S`` and this set of translates is known as a block
        system. Moreover, we obviously have that all blocks in the partition
        have the same size, hence the block size divides ``|S|`` ([1], p.23).
        A ``G``-congruence is an equivalence relation ``~`` on the set ``S``
        such that ``a ~ b`` implies ``g(a) ~ g(b)`` for all ``g`` in ``G``.
        For a transitive group, the equivalence classes of a ``G``-congruence
        and the blocks of a block system are the same thing ([1], p.23).

        The algorithm below checks the group for transitivity, and then finds
        the ``G``-congruence generated by the pairs ``(p_0, p_1), (p_0, p_2),
        ..., (p_0,p_{k-1})`` which is the same as finding the maximal block
        system (i.e., the one with minimum block size) such that
        ``p_0, ..., p_{k-1}`` are in the same block ([1], p.83).

        It is an implementation of Atkinson's algorithm, as suggested in [1],
        and manipulates an equivalence relation on the set ``S`` using a
        union-find data structure. The running time is just above
        `O(|points||S|)`. ([1], pp. 83-87; [7]).

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import DihedralGroup
        >>> D = DihedralGroup(10)
        >>> D.minimal_block([0, 5])
        [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
        >>> D.minimal_block([0, 1])
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

        See Also
        ========

        _union_find_rep, _union_find_merge, is_transitive, is_primitive

        Fr7   r   r   )r  r5   ru   r8   r<   r=   r   r   r   r   r   
setdefault)rd   pointsr   r   r   r   r   r   rD   len_not_repr   r   deltar   new_repsr   s                   r/   r  zPermutationGroup.minimal_block	  s   ` !!#KKuQx.AKt||3q5Lq1u 	*A%+AYGF1q5M"NN6!a%=)	* fQi!e+oAJEFA 
$ ,,UG< --c%j#e*e.5w@2:3q5Lt#
$ +o q 	-A   G,	- 6?6HIda##Aq)IIIs    E c                     |h}|}t        |      dkD  rct               }|D ]2  }| j                  D ]!  }||z  | z  }||vs|j                  |       # 4 |j	                  |       |}t        |      dkD  rc|S )a|  Return the conjugacy class of an element in the group.

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

        The conjugacy class of an element ``g`` in a group ``G`` is the set of
        elements ``x`` in ``G`` that are conjugate with ``g``, i.e. for which

            ``g = xax^{-1}``

        for some ``a`` in ``G``.

        Note that conjugacy is an equivalence relation, and therefore that
        conjugacy classes are partitions of ``G``. For a list of all the
        conjugacy classes of the group, use the conjugacy_classes() method.

        In a permutation group, each conjugacy class corresponds to a particular
        `cycle structure': for example, in ``S_3``, the conjugacy classes are:

            * the identity class, ``{()}``
            * all transpositions, ``{(1 2), (1 3), (2 3)}``
            * all 3-cycles, ``{(1 2 3), (1 3 2)}``

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, SymmetricGroup
        >>> S3 = SymmetricGroup(3)
        >>> S3.conjugacy_class(Permutation(0, 1, 2))
        {(0 1 2), (0 2 1)}

        Notes
        =====

        This procedure computes the conjugacy class directly by finding the
        orbit of the element under conjugation in G. This algorithm is only
        feasible for permutation groups of relatively small order, but is like
        the orbit() function itself in that respect.
        r   )r=   rt   ru   rk  update)rd   r   	new_classlast_iterationthis_iterationr   rT  
conjugateds           r/   conjugacy_classz PermutationGroup.conjugacy_class>
  s    T C	".!A% UN# 7 7A!"Q1"J!2&**:677 ^,+N .!A% rf   c                    t        t        t        | j                                    }|h}|j	                         g}| j                         D ]:  }||vs| j                  |      }|j                  |       |j                  |       < |S )a,  Return the conjugacy classes of the group.

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

        As described in the documentation for the .conjugacy_class() function,
        conjugacy is an equivalence relation on a group G which partitions the
        set of elements. This method returns a list of all these conjugacy
        classes of G.

        Examples
        ========

        >>> from sympy.combinatorics import SymmetricGroup
        >>> SymmetricGroup(3).conjugacy_classes()
        [{(2)}, {(0 1 2), (0 2 1)}, {(0 2), (1 2), (2)(0 1)}]

        )	r>   r8   r<   r5   r  rc  r  r   r  )rd   r   known_elementsclassesr   r  s         r/   conjugacy_classesz"PermutationGroup.conjugacy_classesz
  s    & 4dkk 234"!&&() 	1A& 003	y)%%i0		1 rf   c                    t        |d      r| j                  }t        t        t	        |                  t        fd|j                  D              r|S t        |j                  dd       }|j                         \  }}t        ||      }t        ||      \  }}	| j                  dd       d}
|
r?|j                  dd       t	        |      D ]  }| j                         }|j                         }||z  }t        ||||	      }|d   k7  s|d	   t        |      d	z   k7  sS|j                  }|j                  |       t        |      }|j                  |       |j                  ||      \  }}||}}t        ||      }t        ||      \  }}	 d
}
| j                  D ]J  }|j                  D ]5  }||z  }t        ||||	      }|d   k7  s|d	   t        |      d	z   k7  s3d}
 n |
sJ n |
r?|S t        |d      r| j!                  t        |            S t        |d      r| j!                  t        |g            S y)a  Return the normal closure of a subgroup/set of permutations.

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

        If ``S`` is a subset of a group ``G``, the normal closure of ``A`` in ``G``
        is defined as the intersection of all normal subgroups of ``G`` that
        contain ``A`` ([1], p.14). Alternatively, it is the group generated by
        the conjugates ``x^{-1}yx`` for ``x`` a generator of ``G`` and ``y`` a
        generator of the subgroup ``\left\langle S\right\rangle`` generated by
        ``S`` (for some chosen generating set for ``\left\langle S\right\rangle``)
        ([1], p.73).

        Parameters
        ==========

        other
            a subgroup/list of permutations/single permutation
        k
            an implementation-specific parameter that determines the number
            of conjugates that are adjoined to ``other`` at once

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import (SymmetricGroup,
        ... CyclicGroup, AlternatingGroup)
        >>> S = SymmetricGroup(5)
        >>> C = CyclicGroup(5)
        >>> G = S.normal_closure(C)
        >>> G.order()
        60
        >>> G.is_subgroup(AlternatingGroup(5))
        True

        See Also
        ========

        commutator, derived_subgroup, random_pr

        Notes
        =====

        The algorithm is described in [1], pp. 73-74; it makes use of the
        generation of random elements for permutation groups by the product
        replacement algorithm.

        ru   c              3   (   K   | ]	  }|k(    y wr*   r   r  s     r/   r0   z2PermutationGroup.normal_closure.<locals>.<genexpr>
  s     ;Q1=;r  N
      )r   r   Tr   r7   Frj   r.  )r/  r5   r>   r8   r<   r   ru   r&   r2  r   r   r   r   r   r=   r   r@  )rd   rv   r   r5   Zr   r   r   r   r   _loopr   rE   r   conjrH  r   	temp_basetemp_strong_gensr   s                      @r/   r@  zPermutationGroup.normal_closure
  sh   b 5,'[[FtE&M23H;%*:*:;; !1!1!!45A ! ; ; =D+ 8{ K.t5FG -L,   2 ,E!!B"!-q 3A(AAQ3D t\;MNC1v)SVs4y1}-D ||D),T2#**4077kJ 4	#3,57Gk4T;G * ;4 13 9&83$  	A\\ " s$T4%79q6X-Q3t9q=1H$(E!" 	+ > HUM*&&'7'>??UL)&&'7'@AA *rf   c                 F    t        | j                  | j                  ||      S )a  Compute the orbit of alpha `\{g(\alpha) | g \in G\}` as a set.

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

        The time complexity of the algorithm used here is `O(|Orb|*r)` where
        `|Orb|` is the size of the orbit and ``r`` is the number of generators of
        the group. For a more detailed analysis, see [1], p.78, [2], pp. 19-21.
        Here alpha can be a single point, or a list of points.

        If alpha is a single point, the ordinary orbit is computed.
        if alpha is a list of points, there are three available options:

        'union' - computes the union of the orbits of the points in the list
        'tuples' - computes the orbit of the list interpreted as an ordered
        tuple under the group action ( i.e., g((1,2,3)) = (g(1), g(2), g(3)) )
        'sets' - computes the orbit of the list interpreted as a sets

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation([1, 2, 0, 4, 5, 6, 3])
        >>> G = PermutationGroup([a])
        >>> G.orbit(0)
        {0, 1, 2}
        >>> G.orbit([0, 4], 'union')
        {0, 1, 2, 3, 4, 5, 6}

        See Also
        ========

        orbit_transversal

        )r   r5   ru   )rd   r  actions      r/   r9  zPermutationGroup.orbit
  s    H dkk4??E6BBrf   c                 v   || j                  |      }||   y||   }| j                  D cg c]  }|j                   }}g }|dk7  r3|j                  ||          ||   j	                  |      }||   }|dk7  r3|rt        t        |       S t        t        t        | j                                    S c c}w )a3  Return a group element which sends ``alpha`` to ``beta``.

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

        If ``beta`` is not in the orbit of ``alpha``, the function returns
        ``False``. This implementation makes use of the schreier vector.
        For a proof of correctness, see [1], p.80

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import AlternatingGroup
        >>> G = AlternatingGroup(5)
        >>> G.orbit_rep(0, 4)
        (0 4 1 2 3)

        See Also
        ========

        schreier_vector

        Fr   )
r   ru   r   r   r   r>   r   r8   r<   rZ   )rd   r  r  r   r   r   r   r.   s           r/   	orbit_repzPermutationGroup.orbit_rep$  s    0 ""2259O4 (D!'+7!772gHHT!W7==&D%A 2g 9a=))4dll 3455 8s   B6c                 F    t        | j                  | j                  ||      S )a4  Computes a transversal for the orbit of ``alpha`` as a set.

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

        For a permutation group `G`, a transversal for the orbit
        `Orb = \{g(\alpha) | g \in G\}` is a set
        `\{g_\beta | g_\beta(\alpha) = \beta\}` for `\beta \in Orb`.
        Note that there may be more than one possible transversal.
        If ``pairs`` is set to ``True``, it returns the list of pairs
        `(\beta, g_\beta)`. For a proof of correctness, see [1], p.79

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import DihedralGroup
        >>> G = DihedralGroup(6)
        >>> G.orbit_transversal(0)
        [(5), (0 1 2 3 4 5), (0 5)(1 4)(2 3), (0 2 4)(1 3 5), (5)(0 4)(1 3), (0 3)(1 4)(2 5)]

        See Also
        ========

        orbit

        )_orbit_transversalrZ   ru   )rd   r  r  s      r/   r4  z"PermutationGroup.orbit_transversalL  s    6 "$,,NNrf   c                 B    t        | j                  | j                        S )a  Return the orbits of ``self``, ordered according to lowest element
        in each orbit.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation(1, 5)(2, 3)(4, 0, 6)
        >>> b = Permutation(1, 5)(3, 4)(2, 6, 0)
        >>> G = PermutationGroup([a, b])
        >>> G.orbits()
        [{0, 2, 3, 4, 6}, {1, 5}]
        )_orbitsrZ   rH   )rd   r   s     r/   r   zPermutationGroup.orbitsi  s     t||T%5%566rf   c                 |   | j                   | j                   S | j                  r(| j                  }t        |      | _         | j                   S | j                  r+| j                  }t        |      dz  | _         | j                   S t        | j                  D cg c]  }t        |       c}      }|| _         |S c c}w )aD  Return the order of the group: the number of permutations that
        can be generated from elements of the group.

        The number of permutations comprising the group is given by
        ``len(group)``; the length of each permutation in the group is
        given by ``group.size``.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup

        >>> a = Permutation([1, 0, 2])
        >>> G = PermutationGroup([a])
        >>> G.degree
        3
        >>> len(G)
        1
        >>> G.order()
        2
        >>> list(G.generate())
        [(2), (2)(0 1)]

        >>> a = Permutation([0, 2, 1])
        >>> b = Permutation([1, 0, 2])
        >>> G = PermutationGroup([a, b])
        >>> G.order()
        6

        See Also
        ========

        degree

        r   )rI   rN   rZ   r   rO   r   r   r=   )rd   r   r   r\  s       r/   r   zPermutationGroup.ordery  s    H ;;";;<<A#A,DK;;<<A#A,q.DK;;$"9"9:Q#a&:; ;s   B9c                 h    |j                  |       r!| j                         |j                         z  S y)aX  
        Returns the index of a permutation group.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation(1,2,3)
        >>> b =Permutation(3)
        >>> G = PermutationGroup([a])
        >>> H = PermutationGroup([b])
        >>> G.index(H)
        3

        N)r   r   )rd   r   s     r/   r   zPermutationGroup.index  s,      ==::<** rf   c                 h   | j                   }||S | j                  }|dk\  r| j                         r`| j                         }|r<t	        d | j
                  D              rd\  | _         | _        yd\  | _         | _        y| j                  d      S d\  | _         | _        y| j                  d      S )	a  Return ``True`` if the group is symmetric.

        Examples
        ========

        >>> from sympy.combinatorics import SymmetricGroup
        >>> g = SymmetricGroup(5)
        >>> g.is_symmetric
        True

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> g = PermutationGroup(
        ...     Permutation(0, 1, 2, 3, 4),
        ...     Permutation(2, 3))
        >>> g.is_symmetric
        True

        Notes
        =====

        This uses a naive test involving the computation of the full
        group order.
        If you need more quicker taxonomy for large groups, you can use
        :meth:`PermutationGroup.is_alt_sym`.
        However, :meth:`PermutationGroup.is_alt_sym` may not be accurate
        and is not able to distinguish between an alternating group and
        a symmetric group.

        See Also
        ========

        is_alt_sym
        r  c              3   4   K   | ]  }|j                     y wr*   )is_oddr   s     r/   r0   z0PermutationGroup.is_symmetric.<locals>.<genexpr>  s     =188=r4   TFTFTF)r  r  )rN   r5   r  r  r9   ru   rO   r  )rd   rN   r   _is_alt_syms       r/   is_symmetriczPermutationGroup.is_symmetric  s    F ,,NKK6!!#"??A=T__==5@2dl#1<.DL$, 22D2AA)5&DL$,**D*99rf   c                 h   | j                   }||S | j                  }|dk\  r| j                         r`| j                         }|r<t	        d | j
                  D              rd\  | _        | _         yd\  | _        | _         y| j                  d      S d\  | _        | _         y| j                  d      S )	a  Return ``True`` if the group is alternating.

        Examples
        ========

        >>> from sympy.combinatorics import AlternatingGroup
        >>> g = AlternatingGroup(5)
        >>> g.is_alternating
        True

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> g = PermutationGroup(
        ...     Permutation(0, 1, 2, 3, 4),
        ...     Permutation(2, 3, 4))
        >>> g.is_alternating
        True

        Notes
        =====

        This uses a naive test involving the computation of the full
        group order.
        If you need more quicker taxonomy for large groups, you can use
        :meth:`PermutationGroup.is_alt_sym`.
        However, :meth:`PermutationGroup.is_alt_sym` may not be accurate
        and is not able to distinguish between an alternating group and
        a symmetric group.

        See Also
        ========

        is_alt_sym
        r  c              3   4   K   | ]  }|j                     y wr*   is_evenr   s     r/   r0   z2PermutationGroup.is_alternating.<locals>.<genexpr>&  s     >199>r4   r  Tr  F)r  r  )rO   r5   r  r  r   ru   rN   r  )rd   rO   r   r  s       r/   is_alternatingzPermutationGroup.is_alternating  s    F ,,NKK6!!#"??A>doo>>5@2dl#1<.DL$, 22D2AA)5&DL$,**D*99rf   c                     t        |      }t        |      }t        |      D ]'  }t        |dz   |      D ]  }||   ||   z  dk(  s  y ) y)zKSubroutine to test if there is only one cyclic group for the
        order.r7   NT)r   r=   r<   )rA   primesr   rD   r;  s        r/   _distinct_primes_lemmaz'PermutationGroup._distinct_primes_lemma4  s_     Kq 	 A1Q3]  !9vay(A- 	  rf   c                      j                    j                   S t         j                        dk(  rd _         d _        y j                  du rd _         y j	                         dk  rd _        dk7  rd _         yt              }t        d |j                         D              rS j                  rd _         yt        |j                               }t        j                  |      du rd _         d _        y j                  sd _         yt         fd|j                         D               _          j                   S )a1  
        Return ``True`` if the group is Cyclic.

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import AbelianGroup
        >>> G = AbelianGroup(3, 4)
        >>> G.is_cyclic
        True
        >>> G = AbelianGroup(4, 4)
        >>> G.is_cyclic
        False

        Notes
        =====

        If the order of a group $n$ can be factored into the distinct
        primes $p_1, p_2, \dots , p_s$ and if

        .. math::
            \forall i, j \in \{1, 2, \dots, s \}:
            p_i \not \equiv 1 \pmod {p_j}

        holds true, there is only one group of the order $n$ which
        is a cyclic group [1]_. This is a generalization of the lemma
        that the group of order $15, 35, \dots$ are cyclic.

        And also, these additional lemmas can be used to test if a
        group is cyclic if the order of the group is already found.

        - If the group is abelian and the order of the group is
          square-free, the group is cyclic.
        - If the order of the group is less than $6$ and is not $4$, the
          group is cyclic.
        - If the order of the group is prime, the group is cyclic.

        References
        ==========

        .. [1] 1978: John S. Rose: A Course on Group Theory,
            Introduction to Finite Group Theory: 1.4
        r7   TF      c              3   &   K   | ]	  }|d k(    yw)r7   Nr   )r-   r]  s     r/   r0   z-PermutationGroup.is_cyclic.<locals>.<genexpr>  s     0!qAv0r  c              3   p   K   | ],  \  }|d kD  r"t        fdj                  D               . yw)r7   c              3   H   K   | ]  }|z  z  j                   k7    y wr*   )r   )r-   rE   r   r   rd   s     r/   r0   z7PermutationGroup.is_cyclic.<locals>.<genexpr>.<genexpr>  s"     H1E1H.Hs   "N)r9   ru   )r-   r   r   r   rd   s     @r/   r0   z-PermutationGroup.is_cyclic.<locals>.<genexpr>  s2      
11q5 HHH
s   26)rW   r=   ru   rL   r   r   r   r   r8   keysr&   r   r  r   )rd   rL  r  r   s   `  @r/   	is_cycliczPermutationGroup.is_cyclic@  s#   Z ??&??"t1$"DO#Du$#DO

19#Dz"&E"0w~~/00"&',,.)F66v>$F"&#' #DO 

 
 rf   c                 |   | j                   | j                   S | j                         }|dz  dk(  rd| _         y|dk(  rd| _         y|dk(  r| j                   | _         | j                   S | j                  rd| _         y|dz  }| j                  }t        |      dk(  rg|\  }}|j                         |j                         }}||k  r||||f\  }}}}|dcxk(  r|k(  r	d| _         y ||k(  r|dk(  r||z  |z  | k(  rd| _         yg g }	}| j                  D ]@  }
|
j                         }|dk(  r|j                  |
       *||k(  s0|	j                  |
       B t        |      |dz   |dz  z
  k7  rd| _         y|	sd| _         y|	d   }|d   }|dz  dk(  r|||dz  z  k(  r|d   }||z  |z  | k(  | _         | j                   S )a  
        Return ``True`` if the group is dihedral.

        Examples
        ========

        >>> from sympy.combinatorics.perm_groups import PermutationGroup
        >>> from sympy.combinatorics.permutations import Permutation
        >>> from sympy.combinatorics.named_groups import SymmetricGroup, CyclicGroup
        >>> G = PermutationGroup(Permutation(1, 6)(2, 5)(3, 4), Permutation(0, 1, 2, 3, 4, 5, 6))
        >>> G.is_dihedral
        True
        >>> G = SymmetricGroup(3)
        >>> G.is_dihedral
        True
        >>> G = CyclicGroup(6)
        >>> G.is_dihedral
        False

        References
        ==========

        .. [Di1] https://math.stackexchange.com/questions/827230/given-a-cayley-table-is-there-an-algorithm-to-determine-if-it-is-a-dihedral-gro/827273#827273
        .. [Di2] https://kconrad.math.uconn.edu/blurbs/grouptheory/dihedral.pdf
        .. [Di3] https://kconrad.math.uconn.edu/blurbs/grouptheory/dihedral2.pdf
        .. [Di4] https://en.wikipedia.org/wiki/Dihedral_group
        r   r7   FTr#  r   )rX   r   r(  r  ru   r=   r   r   )rd   r   r   r   r   r   r.   r   order_2order_nr   r   s               r/   is_dihedralzPermutationGroup.is_dihedral  s   : ($$$

19> %DA: $DA:$(NN 2D$$$?? %D QJ t9>DAq779aggiqA1u1aZ
1aA{{$(!  Av!q&QqSUqb[$(! r 	"A	AAvq!aq!	" w<1q5AE?* %D %DAJ AJq5A:!q1a4y.
AqSUqb[   rf   c                 |   |r| j                  |      \  }}g }| j                  }|D ]-  }|D cg c]
  } ||       c}|k(  s|j                  |       / |st        t	        t        |                  }t        |      S | j                  }	| j                  }|D ]  }
t        ||	|
      }	 t        |	      S c c}w )a  Return the pointwise stabilizer for a set of points.

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

        For a permutation group `G` and a set of points
        `\{p_1, p_2,\ldots, p_k\}`, the pointwise stabilizer of
        `p_1, p_2, \ldots, p_k` is defined as
        `G_{p_1,\ldots, p_k} =
        \{g\in G | g(p_i) = p_i \forall i\in\{1, 2,\ldots,k\}\}` ([1],p20).
        It is a subgroup of `G`.

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import SymmetricGroup
        >>> S = SymmetricGroup(7)
        >>> Stab = S.pointwise_stabilizer([2, 3, 5])
        >>> Stab.is_subgroup(S.stabilizer(2).stabilizer(3).stabilizer(5))
        True

        See Also
        ========

        stabilizer, schreier_sims_incremental

        Notes
        =====

        When incremental == True,
        rather than the obvious implementation using successive calls to
        ``.stabilizer()``, this uses the incremental Schreier-Sims algorithm
        to obtain a base with starting segment - the given points.

        r   )	r2  r5   r   r>   r8   r<   r&   rH   _stabilizer)rd   r  incrementalr   r   	stab_gensr5   r   r:  r   r   s              r/   pointwise_stabilizerz%PermutationGroup.pointwise_stabilizer  s    H  $ > >F > KD+I[[F" *,235CJ3v=$$S)* #Dv$78	#I..##D[[F 4"6434%% 4s   B9c                 b   t        |      r|t        d      t        |      |}}n	 t        |      }t        |      }t        t        t        | j                                    }t        |       }t        |      D ]  }|  ||         }t        ||      } |S # t        $ r t        d      w xY w)a5  
        Multiply ``n`` randomly selected permutations from
        pgroup together, starting with the identity
        permutation. If ``n`` is a list of integers, those
        integers will be used to select the permutations and they
        will be applied in L to R order: make_perm((A, B, C)) will
        give CBA(I) where I is the identity permutation.

        ``seed`` is used to set the seed for the random selection
        of permutations from pgroup. If this is a list of integers,
        the corresponding permutations from pgroup will be selected
        in the order give. This is mainly used for testing purposes.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a, b = [Permutation([1, 0, 3, 2]), Permutation([1, 3, 0, 2])]
        >>> G = PermutationGroup([a, b])
        >>> G.make_perm(1, [0])
        (0 1)(2 3)
        >>> G.make_perm(3, [0, 1, 0])
        (0 2 3 1)
        >>> G.make_perm([0, 1, 0])
        (0 2 3 1)

        See Also
        ========

        random
        z'If n is a sequence, seed should be Nonez#n must be an integer or a sequence.)r#   r   r=   r  rl   r   r   r8   r<   r5   r   )rd   r   seedrandomrangeresultr\  r   r   s           r/   	make_permzPermutationGroup.make_perm-  s    @ q> !JKK!fatAHF !& T%"456Iq 	%A[^$A&!_F	%   H !FGGHs   B B.c                 X    t        | j                               }| j                  ||      S )z&Return a random group element
        )r   r   r_  )rd   r[  rW  s      r/   randomzPermutationGroup.random`  s'     &  r**rf   c                 ,   | j                   g k(  r| j                  ||       | j                   }t        |      dz
  }|>t        |      }t        |dz
        }||k(  r|dz
  }t	        ddg      }t	        ddg      }	n|d   }|d   }||k(  r|dz
  }|d   }|d   }	|dk(  r5t        ||   t        ||   |	            ||<   t        ||   ||         ||<   n4t        t        ||   |	      ||         ||<   t        ||   ||         ||<   t        ||         S )a  Return a random group element using product replacement.

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

        For the details of the product replacement algorithm, see
        ``_random_pr_init`` In ``random_pr`` the actual 'product replacement'
        is performed. Notice that if the attribute ``_random_gens``
        is empty, it needs to be initialized by ``_random_pr_init``.

        See Also
        ========

        _random_pr_init

        r7   r   r   rT  r   r   r   )ra   r   r=   r   r   r   r   r>   )
rd   	gen_count
iterationsr   r   r   rT  r   r   r   s
             r/   r   zPermutationGroup.random_prf  sA   " "  J7''q  !A!a% AAvE1vAAwAS!AS!AAvES!AS!A6%k!ngk!na6PQKN%k!nk!nEKN%gk!na&@+a.QKN%k!nk!nEKN{1~&&rf   c                     || j                  |      }|| j                         }n|d   } ||      }| j                  |||      }t        | |      S )a  Random element from the stabilizer of ``alpha``.

        The schreier vector for ``alpha`` is an optional argument used
        for speeding up repeated calls. The algorithm is described in [1], p.81

        See Also
        ========

        random_pr, orbit_rep

        rand)r   r   r  r   )rd   r  r   r   r=  r  r   s          r/   r   zPermutationGroup.random_stab  s_     ""2259O>>#D'DE{NN5$8QB~rf   c                 >    | j                   ry| j                          y)a  Schreier-Sims algorithm.

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

        It computes the generators of the chain of stabilizers
        `G > G_{b_1} > .. > G_{b1,..,b_r} > 1`
        in which `G_{b_1,..,b_i}` stabilizes `b_1,..,b_i`,
        and the corresponding ``s`` cosets.
        An element of the group can be written as the product
        `h_1*..*h_s`.

        We use the incremental Schreier-Sims algorithm.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation([0, 2, 1])
        >>> b = Permutation([1, 0, 2])
        >>> G = PermutationGroup([a, b])
        >>> G.schreier_sims()
        >>> G.basic_transversals
        [{0: (2)(0 1), 1: (2), 2: (1 2)},
         {0: (2), 2: (0 2)}]
        N)r_   r   rq   s    r/   r   zPermutationGroup.schreier_sims  s    6 rf   c           	         | j                  |d      }|d d \  }}|| _        || _        |d   | _        |sg | _        g | _        y t        ||      }t        ||d      \  }}}t        |      D ]9  \  }}	||   }
|	D ]*  }|	|   D cg c]  }|j                  |
|          c}|	|<   , ; || _        |D cg c]  }t        |       c}| _        || _        y c c}w c c}w )NT)r   slp_dictr   )rS  )r2  r[   r\   r]   r_   r^   r   r   r   r   r   r`   )rd   r   schreierr   r   r   r   slpsrD   rS  r   r   rT  r   s                 r/   r   zPermutationGroup._schreier_sims  s   11td1K$RaLk
' (!#D!#D4T;G+I$!t,-(lD  o 	FFAs$Q'D F>A!fE+++DG4EAF	F
 *1=>AfQi> $	 F ?s   C5Cc                   & |g }|| j                   dd }| j                  }t        t        |            }t	        |      dk(  r#|d   j
                  r|r|||d   |d   gifS ||fS |dd |dd }}|D cg c]  }|j
                  r| }}|D ]E  &t        &fd|D              s|D ]  }	&j                  |	   |	k7  s n J |j                  |	       G t        ||      }
g }i }i }i }t	        |      }t        |      D ]R  }t        ||
|   ||   ddd      \  ||<   ||<   t        ||         ||<   t        ||   j                               ||<   T |dz
  }|dk\  rd}i }t        ||   j                               D ]  \  }}t        |
|         D ]  \  }&&j                  |   }||   |   }t        &j                  |      }||   |   D cg c]  }||f }}||fg|z   }||k7  rHd}	 ||   }t        ||      }||   |   dd }|j%                          |D cg c]  }||ff	 }}||z   }t'        |||||||      \  }}}||k  rd}nC|rAd}d} ||    | k(  r| dz  } ||    | k(  r|j                  |        |dz  }|
j                  g        |du rt)        |      }|j                  ||f       t        |dz   |      D ]f  }!|
|!   j                  |       t        ||
|!   ||!   ddd      \  ||!<   ||!<   t        ||!         ||!<   t        ||!   j                               ||!<   h |dz
  }d}|du s n |du s n |du r|dz  }|dk\  r|dd }"|r|D ]p  \  }#}|"j                  |#       t        t	        |            D ]C  }||   }$t+        |$d   t,              r|
|$d      |$d   d      d	z  ||<   3|
|$d      |$d      ||<   E r t        |      }|D ]  }|g||<   
 ||"|fS |"j/                  |D #%cg c]  \  }#}%|#	 c}%}#       ||"fS c c}w c c}w # t         $ r t#        |      x}||<   Y Kw xY wc c}w c c}%}#w )
a  Extend a sequence of points and generating set to a base and strong
        generating set.

        Parameters
        ==========

        base
            The sequence of points to be extended to a base. Optional
            parameter with default value ``[]``.
        gens
            The generating set to be extended to a strong generating set
            relative to the base obtained. Optional parameter with default
            value ``self.generators``.

        slp_dict
            If `True`, return a dictionary `{g: gens}` for each strong
            generator `g` where `gens` is a list of strong generators
            coming before `g` in `strong_gens`, such that the product
            of the elements of `gens` is equal to `g`.

        Returns
        =======

        (base, strong_gens)
            ``base`` is the base obtained, and ``strong_gens`` is the strong
            generating set relative to it. The original parameters ``base``,
            ``gens`` remain unchanged.

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import AlternatingGroup
        >>> from sympy.combinatorics.testutil import _verify_bsgs
        >>> A = AlternatingGroup(7)
        >>> base = [2, 3]
        >>> seq = [2, 3]
        >>> base, strong_gens = A.schreier_sims_incremental(base=seq)
        >>> _verify_bsgs(A, base, strong_gens)
        True
        >>> base[:2]
        [2, 3]

        Notes
        =====

        This version of the Schreier-Sims algorithm runs in polynomial time.
        There are certain assumptions in the implementation - if the trivial
        group is provided, ``base`` and ``gens`` are returned immediately,
        as any sequence of points is a base for the trivial group. If the
        identity is present in the generators ``gens``, it is removed as
        it is a redundant generator.
        The implementation is described in [1], pp. 90-93.

        See Also
        ========

        schreier_sims, schreier_sims_random

        Nr7   r   c              3   B   K   | ]  }|j                   |   k(    y wr*   r"  r-   r   r   s     r/   r0   z=PermutationGroup.schreier_sims_incremental.<locals>.<genexpr>0  s     :q1**:s   T)r  r[  rS  F)rS  rB  r   )ru   r5   r8   r<   r=   r  r   r   r   r   r  r3  r'  r   r   r   KeyErrorr
   reverser   r>   r+   rj  r   )'rd   r   r   r@  r5   id_afr[   _gensr   r   r   strong_gens_slporbsr   rB  r   rD   
continue_idbr  u_betar;  gbu1r  rE   rS  r   u1_invschreier_gen
u1_inv_slpr   movedr   r   r   rT  r   r   s'                                         @r/   r2  z*PermutationGroup.schreier_sims_incremental  sh   x <D<??1%DU6]#t9>d1g11TDGd1gY#777:AwQu!7q77 	"C:E::   Cs+s2   4S!	" 5UEBu:x 	3A'9&BSTUBVa4(9$LOT!W"<?3LO<?//12DG		3 qL1f JB $\!_%:%:%< = 3f'(9!(<= 0FAs.B%a,B!#//6:B+/74=9aAq69C9q6(S.CRx !=%'VF (0';%)!WR[^
"**,9C%DAq1$i%D
%D(3.$-lE4WX^ahl$m	1c= %A %A$%E"#E(e"3 %
 #$E(e"3!LL/$MH-44R8: !(
A+22As8<%*1q5!_ G 1! 4 ; ;A > 26;LQ;O$)!HDTt!M !9Qa 37|A2GQ*.|A/C/C/E*FQG !"AA)-J!T)a0b %g3h T!FAy 1f| Ah * ?3""1%s3x ?AAA!!A$.!21Q4!81a!A2!EA!21Q4!81!>A?? #?3O )&'S");88/:$!QA:;k!![ 8J :  ( =.8n<FRV=
 &Et ;s0   6PPP"3P'#QQ
'QQc           	      R   |g }|| j                   }t        |      }| j                  }|D ]Y  t        fd|D              sd}j                  |   |k(  r|dz  }j                  |   |k(  r|j                  |       |dz  }[ t        ||      }i }	i }
t        |      D ]B  }t        t        |||   ||   d            |	|<   t        |	|   j                               |
|<   D d}||k  r|| j                         }n|d   j                         }t        |||
|	      \  }}d}||k  rd}nS|j                  sGd}d} ||      |k(  r|dz  } ||      |k(  r|j                  |       |dz  }|j                  g        |du rht        d|      D ]V  }||   j                  |       t        t        |||   ||   d            |	|<   t        |	|   j                               |
|<   X d}n|dz  }||k  r|d   dd }|d   D ]  |vs|j                          ||fS )	a	  Randomized Schreier-Sims algorithm.

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

        The randomized Schreier-Sims algorithm takes the sequence ``base``
        and the generating set ``gens``, and extends ``base`` to a base, and
        ``gens`` to a strong generating set relative to that base with
        probability of a wrong answer at most `2^{-consec\_succ}`,
        provided the random generators are sufficiently random.

        Parameters
        ==========

        base
            The sequence to be extended to a base.
        gens
            The generating set to be extended to a strong generating set.
        consec_succ
            The parameter defining the probability of a wrong answer.
        _random_prec
            An internal parameter used for testing purposes.

        Returns
        =======

        (base, strong_gens)
            ``base`` is the base and ``strong_gens`` is the strong generating
            set relative to it.

        Examples
        ========

        >>> from sympy.combinatorics.testutil import _verify_bsgs
        >>> from sympy.combinatorics.named_groups import SymmetricGroup
        >>> S = SymmetricGroup(5)
        >>> base, strong_gens = S.schreier_sims_random(consec_succ=5)
        >>> _verify_bsgs(S, base, strong_gens) #doctest: +SKIP
        True

        Notes
        =====

        The algorithm is described in detail in [1], pp. 97-98. It extends
        the orbits ``orbs`` and the permutation groups ``stabs`` to
        basic orbits and basic stabilizers for the base and strong generating
        set produced in the end.
        The idea of the extension process
        is to "sift" random group elements through the stabilizer chain
        and amend the stabilizers/orbits along the way when a sift
        is not successful.
        The helper function ``_strip`` is used to attempt
        to decompose a random group element according to the current
        state of the stabilizer chain and report whether the element was
        fully decomposed (successful sift) or not (unsuccessful sift). In
        the latter case, the level at which the sift failed is reported and
        used to amend ``stabs``, ``base``, ``gens`` and ``orbs`` accordingly.
        The halting condition is for ``consec_succ`` consecutive successful
        sifts to pass. This makes sure that the current ``base`` and ``gens``
        form a BSGS with probability at least `1 - 1/\text{consec\_succ}`.

        See Also
        ========

        schreier_sims

        Nc              3   4   K   | ]  } |      |k(    y wr*   r   rE  s     r/   r0   z8PermutationGroup.schreier_sims_random.<locals>.<genexpr>  s     -13q6Q;-r   r   r7   Tr  rE   F)ru   r=   r5   r   r   r   r   r<   r3  r  r8   r'  r   r:   r   r  )rd   r   r   consec_succr   r   r   r   r   r   rK  rD   r^  rE   r   r;  r   rT  r   r   r   s                       @r/   schreier_sims_randomz%PermutationGroup.schreier_sims_random  s   J <D<??Dt9KK 	C---ooc*c11HC ooc*c1C A	 5T4@x 	3A"#5a9J19MQt$% &LO<?//12DG	3
  +o#NN$ %))+!T46DAqAH}]]h%'QJE h%'E"A!((, Ezq! ;A%a(//2&*+=a)!,d1gT,C 'DLO"<?#7#7#9:DG	;
 Q9 +o< (*1-$Q' 	(C+%""3'	( [  rf   c                    | j                   }dg|z  }d||<   |g}dg|z  }d||<   | j                  }t        |      }|D ]G  }t        |      D ]7  }	||	   j                  |   }
||
   du s|j                  |
       d||
<   |	||
<   9 I |S )a(  Computes the schreier vector for ``alpha``.

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

        The Schreier vector efficiently stores information
        about the orbit of ``alpha``. It can later be used to quickly obtain
        elements of the group that send ``alpha`` to a particular element
        in the orbit. Notice that the Schreier vector depends on the order
        in which the group generators are listed. For a definition, see [3].
        Since list indices start from zero, we adopt the convention to use
        "None" instead of 0 to signify that an element does not belong
        to the orbit.
        For the algorithm and its correctness, see [2], pp.78-80.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation([2, 4, 6, 3, 1, 5, 0])
        >>> b = Permutation([0, 1, 3, 5, 4, 6, 2])
        >>> G = PermutationGroup([a, b])
        >>> G.schreier_vector(0)
        [-1, None, 0, 1, None, 1, 0]

        See Also
        ========

        orbit

        Nr   FT)r5   ru   r=   r<   r   r   )rd   r  r   r]  r  usedr   r   r   rD   r   s              r/   r   z PermutationGroup.schreier_vector   s    @ KKF1H%gwqyUI 	 A1X  Aw**1-:&JJt$!%DJAdG 	  rf   c                 V    t        t        | j                  | j                  |            S )a  Return the stabilizer subgroup of ``alpha``.

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

        The stabilizer of `\alpha` is the group `G_\alpha =
        \{g \in G | g(\alpha) = \alpha\}`.
        For a proof of correctness, see [1], p.79.

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import DihedralGroup
        >>> G = DihedralGroup(6)
        >>> G.stabilizer(5)
        PermutationGroup([
            (5)(0 4)(1 3)])

        See Also
        ========

        orbit

        )r  r.  rZ   rH   )rd   r  s     r/   r  zPermutationGroup.stabilizerQ  s"    2 T\\43C3CUKLLrf   c                 X    | j                   g k(  r| j                          | j                   S )a   Return a strong generating set from the Schreier-Sims algorithm.

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

        A generating set `S = \{g_1, g_2, \dots, g_t\}` for a permutation group
        `G` is a strong generating set relative to the sequence of points
        (referred to as a "base") `(b_1, b_2, \dots, b_k)` if, for
        `1 \leq i \leq k` we have that the intersection of the pointwise
        stabilizer `G^{(i+1)} := G_{b_1, b_2, \dots, b_i}` with `S` generates
        the pointwise stabilizer `G^{(i+1)}`. The concepts of a base and
        strong generating set and their applications are discussed in depth
        in [1], pp. 87-89 and [2], pp. 55-57.

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import DihedralGroup
        >>> D = DihedralGroup(4)
        >>> D.strong_gens
        [(0 1 2 3), (0 3)(1 2), (1 3)]
        >>> D.base
        [0, 1]

        See Also
        ========

        base, basic_transversals, basic_orbits, basic_stabilizers

        )r\   r   rq   s    r/   r   zPermutationGroup.strong_gensl  s+    @ "    rf   c                 \     t         fd|D              st        d      t        |      }|S )zp
           Return the subgroup generated by `gens` which is a list of
           elements of the group
        c              3   &   K   | ]  }|v  
 y wr*   r   )r-   rE   rd   s     r/   r0   z,PermutationGroup.subgroup.<locals>.<genexpr>  s     +19+s   z2The group does not contain the supplied generators)r   r   r&   )rd   r   rA  s   `  r/   subgroupzPermutationGroup.subgroup  s.     +d++QRRT"rf   c           	      Z  &'()*+ &fd}&'()*+fd}|| j                         \  }}t        |      }| j                  (t        t	        t        (                  }	t        |(      &&j                  (       &j                  d       t        ||      }
t        ||
      \  '}|t        |	g      }|&d }g }t        |      D ]  }|j                  |        |}|dz
  }|dz
  }|dd }|j                  |      \  }}t        ||      }|j                  }t        |      D cg c]  }t        (||   ||          c}*dg|z  }t        (||         } ||      ||<   ||   j                  ||          dg|z  }|	g|z  }dg|z  +t        |      D ]%  }'|   dd +|<   +|   j                  &fd	
       ' dg|z  }dg|z  )(dz   ||<    ||       |	g|z  }	 ||dz
  k  r ||   ||         ||   v r&||      & ||   ||            cxk  r&)|      k  rn n| ||   |      rp ||   ||         }|||<   t!        (||   |      }|||dz   <   t        (|      } ||      ||dz   <   |dz  }'|   D cg c]  } ||dz
     |       }}|j                  &fd
       |+|<   (dz   }t        |      D ])  }||   *|   v s ||   ||         } &|    &|   kD  s(| }+ |||<    ||       d||<   +|   ||      }!||dz
     j"                  j%                  |!      }"||   |"   ||<   t'        ||dz
     ||         ||<   ||dz
  k  rI ||   ||         ||   v r6&||      & ||   ||            cxk  r&)|      k  rn n ||   |      rp||   }# |#||         }!||dz
  k(  r&||      &|!   cxk  r&)|      k  rn n|!||   v r} ||   |      rr ||#      rj|j                  |#       |dd }|j                  |#       t        ||      }t        |      D cg c]  }t        (||   ||          c}* ||      ||<   |}|dk\  r9||   t        '|         dz
  k(  r"|dz
  }|dk\  r||   t        '|         dz
  k(  r"|dk(  rt        |      S ||k  rn|}d||<   t        (||         }$ ||$      ||<   (dz   ||<   t        '|         dz   t        *|         z
  }%|%t        +|         k\  r	&(   )|<   n+|   |%   )|<   ||xx   dz  cc<   |dk(  r+|   ||      }"n*||dz
     j"                  j%                  +|   ||            }"||   |"   ||<   |dk(  r	||   ||<   nt'        ||dz
     ||         ||<   c c}w c c}w c c}w )a  Find the subgroup of all elements satisfying the property ``prop``.

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

        This is done by a depth-first search with respect to base images that
        uses several tests to prune the search tree.

        Parameters
        ==========

        prop
            The property to be used. Has to be callable on group elements
            and always return ``True`` or ``False``. It is assumed that
            all group elements satisfying ``prop`` indeed form a subgroup.
        base
            A base for the supergroup.
        strong_gens
            A strong generating set for the supergroup.
        tests
            A list of callables of length equal to the length of ``base``.
            These are used to rule out group elements by partial base images,
            so that ``tests[l](g)`` returns False if the element ``g`` is known
            not to satisfy prop base on where g sends the first ``l + 1`` base
            points.
        init_subgroup
            if a subgroup of the sought group is
            known in advance, it can be passed to the function as this
            parameter.

        Returns
        =======

        res
            The subgroup of all elements satisfying ``prop``. The generating
            set for this group is guaranteed to be a strong generating set
            relative to the base ``base``.

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import (SymmetricGroup,
        ... AlternatingGroup)
        >>> from sympy.combinatorics.testutil import _verify_bsgs
        >>> S = SymmetricGroup(7)
        >>> prop_even = lambda x: x.is_even
        >>> base, strong_gens = S.schreier_sims_incremental()
        >>> G = S.subgroup_search(prop_even, base=base, strong_gens=strong_gens)
        >>> G.is_subgroup(AlternatingGroup(7))
        True
        >>> _verify_bsgs(G, base, G.generators)
        True

        Notes
        =====

        This function is extremely lengthy and complicated and will require
        some careful attention. The implementation is described in
        [1], pp. 114-117, and the comments for the code here follow the lines
        of the pseudocode in the book for clarity.

        The complexity is exponential in general, since the search process by
        itself visits all members of the supergroup. However, there are a lot
        of tests which are used to prune the search tree, and users can define
        their own tests via the ``tests`` parameter, so in practice, and for
        some computations, it's not terrible.

        A crucial part in the procedure is the frequent base change performed
        (this is line 11 in the pseudocode) in order to obtain a new basic
        stabilizer. The book mentiones that this can be done by using
        ``.baseswap(...)``, however the current implementation uses a more
        straightforward way to find the next basic stabilizer - calling the
        function ``.stabilizer(...)`` on the previous basic stabilizer.

        c                 J    | D cg c]  }t        |fd       c}S c c}w )Nc                     |    S r*   r   )r   r   s    r/   r   zDPermutationGroup.subgroup_search.<locals>.get_reps.<locals>.<lambda>  s    }Q/? rf   r   )r  )r   r9  r   s     r/   get_repsz2PermutationGroup.subgroup_search.<locals>.get_reps  s-     "# %?@ # # #s    c                     t        |          dz   t        |          z
  }|t        |          k\  r	   | <   y |    |   | <   y )Nr7   r  )r   
temp_indexr   r   r5   nures_basic_orbits_init_basesorted_orbitss     r/   	update_nuz3PermutationGroup.subgroup_search.<locals>.update_nu  s^    \!_-17:;<J Sq!122%f-1%a(41rf   Nr   c                      yr  r   r  s    r/   r   z2PermutationGroup.subgroup_search.<locals>.<lambda>
  r   rf   r7   r   r   c                     |    S r*   r   r:  r   s    r/   r   z2PermutationGroup.subgroup_search.<locals>.<lambda>+  s    M%4H rf   r   c                     |    S r*   r   rl  s    r/   r   z2PermutationGroup.subgroup_search.<locals>.<lambda>K  s    -2F rf   )r2  r=   r5   r>   r8   r<   r   r   r   r   r&   ru   r   r  r   r1  r.  r   r   r   ),rd   r,  r   r   r-  init_subgrouprc  ri  r   r   r   r   r>  rD   rH  rU  r   res_baseres_strong_gensres_strong_gens_distrres_generatorsr)  r   r^  r  mur#  	new_pointnew_stab_gensr:  
temp_orbitnew_mu	candidate
temp_pointr   rE   temp_orbitsre  r   r   r5   rf  rg  rh  s,                                         @@@@@@r/   r5  z PermutationGroup.subgroup_search  sc   \	#
	5 	5 < $ > > @D+t94f./&tV4V$R 4T;G%CD%6&8"l  ,hZ8M=)LE8_ +\*+ qLqL7$'$A$A %B %!/ 8 /!1 /	# 
-a0(1+	> 	# 	# VH_
!6q!9: (
1 	1T!W%CLJxxx 	JA+Aq1M!!!!&H!I	J VH_VH_
1!"H,hl"!q!$q'*jm;be$/nQ/Q89%be$% E!H^,-N1-d1g6	' +F4I!4L!!#/<%a!e, !7$,V$4
1q5!Q ,Q1u3nQU3E: 1
 1$FG#-a !q /AAw"<Q"??$5N1$5d1g$>	(3mF6KK%.F	/
 1!!*1-ad3
&q1u-99??
K#Au-!$(A)>!$Eq!K hl"!q!$q'*jm;be$/nQ/Q89%be$% E!H^,D q!A47JHqL be$j)A,9"Q%,@Ajm+a(G%%a(7&&q)(@:I)K%  /+  5a 8(1+F + +
 !) 0
1 q&QqTSa%9A%==E q&QqTSa%9A%== Bw'771u!%f.CA.FG ( 5
1
1 a1A521567
]1%5!66)&1BqE)!,Z8BqE aDAIDAv&q)!A$/&q1u-99??a@PQRSTQU@VW?5)AaDAv$%aDq!$(A)>!$Eq!E 5	#\1J+s   )V
V#8V(c                     | j                   e| j                  }| }t        |      D ]@  }|j                  |      }t	        |      ||z
  k7  r|| _         |c S |j                  |      }B || _         |S | j                   S )au  Compute the degree of transitivity of the group.

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

        A permutation group `G` acting on `\Omega = \{0, 1, \dots, n-1\}` is
        ``k``-fold transitive, if, for any `k` points
        `(a_1, a_2, \dots, a_k) \in \Omega` and any `k` points
        `(b_1, b_2, \dots, b_k) \in \Omega` there exists `g \in  G` such that
        `g(a_1) = b_1, g(a_2) = b_2, \dots, g(a_k) = b_k`
        The degree of transitivity of `G` is the maximum ``k`` such that
        `G` is ``k``-fold transitive. ([8])

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup
        >>> a = Permutation([1, 2, 0])
        >>> b = Permutation([1, 0, 2])
        >>> G = PermutationGroup([a, b])
        >>> G.transitivity_degree
        3

        See Also
        ========

        is_transitive, orbit

        )rT   r5   r<   r9  r=   r  )rd   r   rA  rD   r  s        r/   transitivity_degreez$PermutationGroup.transitivity_degree  s    > $$,AA 1X $ggajs8q1u$01D-HLLO$ )*D%H,,,rf   c                    | j                   dd }t        |d d      }|D cg c]  }||j                         |z  z   }}g }t        t	        |            D ]	  }||   }|j                         }|||z  z  }	|dkD  rt        |d|       }
nt        | j                        }
|||z  z  |
vr|j                  |||z  z         l|
j                  |	d      }|D ]
  }||dz  z  } ||z  }||= ||= |dz
  }|t	        |      k  r@||   j                         |k\  r*|dz  }|t	        |      k  r||   j                         |k\  r*|d| |gz   ||d z   }|d| |gz   ||d z   } t        |      S c c}w )	z
        For an abelian p-group, return the subgroup consisting of
        all elements of order p (and the identity)

        Nc                 "    | j                         S r*   r  r  s    r/   r   z4PermutationGroup._p_elements_group.<locals>.<lambda>  s    !'') rf   T)r   rG  r   rP  r   r7   )	ru   r   r   r<   r=   r&   r   r   rR  )rd   r   r   rE   gens_pgens_rrD   r   x_orderx_pPrT  r;  s                r/   _p_elements_groupz"PermutationGroup._p_elements_group  s    q!d 3TB,01q!aggik"11s4y! 	7AQAggiGgai.C1u$VBQZ0$T]]3719~Q&a'!)n- ''d';  A!R%A !!)G1IE#d)mQ7(BFA #d)mQ7(BBQx1#~QR0qc)F12J63	74  ''9 2s   E0c           
         | j                   }g }t        |dz
        }|dk(  xr t        d | j                  D              }g }|}|dkD  r|j	                  ||z         ||z  }|dkD  rt        |      dz
  }t        d|dz         D ]  }	|	dk(  r|rt        t        ||	z        D 
cg c]  }
|
||	dz
  z  z   ||	z  z   c}
      }|j	                  ||z         |sVt        dd      |z  t        dd      z  |z  }|j	                  |        d}|dkD  r||   }t        |      D ]  }t               }|dkD  rt        ||z        D ]  }	 ||	||	z         } |r9t        dd      |z  t        dd      z  |z  }|j	                  |       d|dz
  z  }
n|}
t        |d|
       D ])  \  }	}|r	|	dz  dk(  r||z  |z  }|j	                  |       + |||z  z  } |dz
  }|dkD  r|S c c}
w )a  
        Return a p-Sylow subgroup of a symmetric or an
        alternating group.

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

        The algorithm for this is hinted at in [1], Chapter 4,
        Exercise 4.

        For Sym(n) with n = p^i, the idea is as follows. Partition
        the interval [0..n-1] into p equal parts, each of length p^(i-1):
        [0..p^(i-1)-1], [p^(i-1)..2*p^(i-1)-1]...[(p-1)*p^(i-1)..p^i-1].
        Find a p-Sylow subgroup of Sym(p^(i-1)) (treated as a subgroup
        of ``self``) acting on each of the parts. Call the subgroups
        P_1, P_2...P_p. The generators for the subgroups P_2...P_p
        can be obtained from those of P_1 by applying a "shifting"
        permutation to them, that is, a permutation mapping [0..p^(i-1)-1]
        to the second part (the other parts are obtained by using the shift
        multiple times). The union of this permutation and the generators
        of P_1 is a p-Sylow subgroup of ``self``.

        For n not equal to a power of p, partition
        [0..n-1] in accordance with how n would be written in base p.
        E.g. for p=2 and n=11, 11 = 2^3 + 2^2 + 1 so the partition
        is [[0..7], [8..9], {10}]. To generate a p-Sylow subgroup,
        take the union of the generators for each of the parts.
        For the above example, {(0 1), (0 2)(1 3), (0 4), (1 5)(2 7)}
        from the first part, {(8 9)} from the second part and
        nothing from the third. This gives 4 generators in total, and
        the subgroup they generate is p-Sylow.

        Alternating groups are treated the same except when p=2. In this
        case, (0 1)(s s+1) should be added for an appropriate s (the start
        of a part) for each part in the partitions.

        See Also
        ========

        sylow_subgroup, is_alt_sym

        r7   r   c              3   4   K   | ]  }|j                     y wr*   r  r   s     r/   r0   z2PermutationGroup._sylow_alt_sym.<locals>.<genexpr>"  s     @1QYY@r4   r   N)r5   r   r   ru   r   r=   r<   r   )rd   r   r   r   r   altcoeffsr\  powerrD   r;  r   r   r.   r   shifts                   r/   _sylow_alt_symzPermutationGroup._sylow_alt_sym  s@   V KKqs# 1f@@@@ !eMM!a% QA !e FA q%'" 	!AAv#eAqDkJA!H14JKCKK%!!Q'+K1,==cAC 	! aiuA 1X "#19"1e8_ 4 %a 34 )!Q/5k!Q6GGMC(uqyM!"+D!H"5 )31q5A:$ $CioC() E!+", !GE7 ai: O Ks   %G#
c                    ddl m}m} t              st	        d      fd}fd}| j                         }|z  dk7  rt        | j                  g      S  ||       \  }}|r| S | j                         rt        | j                              S | j                         }	|	D 
cg c]%  }
t        |
      z  dk7  st        |
      dk7  s$|
' }}
|r<| j                  t        |d         j                               }|j                        S | j!                         sNt#        |	t              }	|	j                         } |	d   j$                  |	 } || |      } || |      } |||      S | j'                         }t        |      dkD  r! || |d         } || |d         } |||      S t        |      dk(  rt        |      d   }t)        d |D              ra || |      } ||j+                               d   s?|j+                         j                        }|j-                  |      j                        S | j/                         }|j                         }|z  dk7  s|dk(  r/| j/                         }|j                         }|z  dk7  r)|dk(  r/||z  z  }|d	z  z  dk7  rt        |      S | j1                  |      }|j                         |z  z  dk7  r|j                        }|j                         }|j3                         }|j5                        }|j/                         }| j1                  |      }|j                         z  |z  dk7  r;|j/                         }| j1                  |      }|j                         z  |z  dk7  r;|}|j                         |z  z  dk7  r|j                        S c c}
w )
a	  
        Return a p-Sylow subgroup of the group.

        The algorithm is described in [1], Chapter 4, Section 7

        Examples
        ========
        >>> from sympy.combinatorics.named_groups import DihedralGroup
        >>> from sympy.combinatorics.named_groups import SymmetricGroup
        >>> from sympy.combinatorics.named_groups import AlternatingGroup

        >>> D = DihedralGroup(6)
        >>> S = D.sylow_subgroup(2)
        >>> S.order()
        4
        >>> G = SymmetricGroup(6)
        >>> S = G.sylow_subgroup(5)
        >>> S.order()
        5

        >>> G1 = AlternatingGroup(3)
        >>> G2 = AlternatingGroup(5)
        >>> G3 = AlternatingGroup(9)

        >>> S1 = G1.sylow_subgroup(3)
        >>> S2 = G2.sylow_subgroup(3)
        >>> S3 = G3.sylow_subgroup(3)

        >>> len1 = len(S1.lower_central_series())
        >>> len2 = len(S2.lower_central_series())
        >>> len3 = len(S3.lower_central_series())

        >>> len1 == len2
        True
        >>> len1 < len3
        True

        r   )orbit_homomorphismblock_homomorphismzp must be a primec                 x    | j                         }d}|z  dk(  r|z  }|dz  }|dk(  rd|fS |z  dk(  rd|fS )Nr   r7   TFr  )rA  r\  r   r   s      r/   
is_p_groupz3PermutationGroup.sylow_subgroup.<locals>.is_p_group  sZ     	AAa%1*aCQ67N	 a%1*
 !8Orf   c                     | j                         j                        }| j                  |      }|j                  |      }|j                         j                        }|j                  |      S r*   )imagesylow_subgroupinvert_subgrouprestrict_to)rs  rf  QRr   s       r/   _sylow_reducez6PermutationGroup.sylow_subgroup.<locals>._sylow_reduce  s`     
))!,A""1%A"B
))!,A%%a((rf   r7   r   c              3   &   K   | ]	  }|d k7    ywr  r   r  s     r/   r0   z2PermutationGroup.sylow_subgroup.<locals>.<genexpr>  s     )a16)r  r   )!sympy.combinatorics.homomorphismsr  r  r!   r   r   r&   r   r  r  r   r=   r  r8   r:   r  r  r   unionr  r9   r  r  r8  r  r  r  )rd   r   r  r  r  r  r   p_groupr   r   onon_p_orbitsrA  omega1omega2rs  rf  r  r  SrE   g_orderCs_orderr  r  r   C_hs    `                          r/   r  zPermutationGroup.sylow_subgroup\  s   N	8 qz011
		) 

19>#T]]O44%
K??#D$7$7$:;;
 #)MaSVaZ1_Q1MM\!_ 5 9 9 ;<A##A&&!!#F,FZZ\F$VAY__f-F#D&1B#D&1B R(($$&v;?#D&)4B#D&)4B R(([ALOE)5))'e4!"((*-a0
11!4A--a0??BB KKM'')kQ'Q,AggiG kQ'Q, 11a4<1#A&&Qggi!Q$!#  #AggiG
A##A&A
A""1%C))+/')Q.HHJ&&q) ))+/')Q. A ggi!Q$!# ""i Ns   %O<OOc                    t        | j                  |            }dgt        |      z  }dgt        |      z  }g g}dgt        |      z  }|j                  |d      }|D ]9  \  }	}
|d   j	                  |	       |j                  |	      }d||<   |||<   |
||<   ; d}d}||k  rC||   d   }
| j                  D ]  }|
|z  }|j                  |      }||   }|dk  r|dz  }|}||j                  |
         |z  ||<   |||<   |}|||<   |g}||   dd  D ]p  }|j                  |      }||z  }|j                  |      }||   dk  r'||   |z  ||<   |||<   |||<   |j	                  |       Y||   |z  ||   dz  z  }d|fc c S  |j	                  |       ||   dd  D ]4  }||z  ||   vs||j                  |
         |z  ||   dz  z  }d|fc c S  " |dz  }||k  rCd|fS )Nr   r   Tr  r7   F)r   r9  r=   r4  r   r   ru   )rd   Lr  r  r   r  Br  r   r.   r  i_arhor\  rE   r  i_dsigmar   newbr   i_gammarT  r   s                           r/   _block_verifyzPermutationGroup._block_verify  sm   tzz%() DUOc%jDCE
NT2 	GAtaDKKN++a.CAcFF3KAcF	 QhS6!9D__ !,Fkk!n#19FAEu{{401!3AcF"AcFC"%F3K5D!"3 ,"'++e"4!!G#kk!nS6A:%&wZ\AcF%*AcF*-F3K KKN !"'
1QsVb\ 9A#(!8O, HHTNsVABZ ,Q3ah. !%++d"3 4Q 6qv| CA#(!8O	,;!,D 1HCI QhL V|rf   c           
         | j                  |      }||dz  z  }|j                  |      }||g}t        |D 	ch c]  }	t        |j                  |	             c}	      }
|
D cg c]  }|d   	 }}|D ]  }||vs|j	                  |        ||g}||j                  | j                        ||j                  |dz        i}|j                  |d      D ]$  \  }}||vs||   |j                  |      z  ||<   & |j                  |      j                  |j                  |            }t        |      t        |      k  r|D ]  }||v s||z  }||vs|j	                  |       ||   |j                  |      z  ||<   |j                  |d      D ]$  \  }}||vs||   |j                  |      z  ||<   & |j                  |j                  |            } n t        |      t        |      k  rg }|D ]  }|j                  |      j                  }|D ]  }||   }|j                  |d      }|ddd   D ]  }||j                  |      z  } |||   dz  z  } ||      }	 |j                  |d      }|D ]  }||j                  |      dz  z  } ||vs|j	                  |         |D ]u  }||   |j                  |      z  |||z     dz  z  } ||      }	 |j                  |d      }|D ]  }||j                  |      dz  z  } ||vse|j	                  |       w d|fS c c}	w c c}w # t        $ r d|fcY c c S w xY w# t        $ r	 d|fcY c S w xY w)a(  
        Return a list of relators ``rels`` in generators ``gens`_h` that
        are mapped to ``H.generators`` by ``phi`` so that given a finite
        presentation <gens_k | rels_k> of ``K`` on a subset of ``gens_h``
        <gens_h | rels_k + rels> is a finite presentation of ``H``.

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

        ``H`` should be generated by the union of ``K.generators`` and ``z``
        (a single generator), and ``H.stabilizer(alpha) == K``; ``phi`` is a
        canonical injection from a free group into a permutation group
        containing ``H``.

        The algorithm is described in [1], Chapter 6.

        Examples
        ========

        >>> from sympy.combinatorics import free_group, Permutation, PermutationGroup
        >>> from sympy.combinatorics.homomorphisms import homomorphism
        >>> from sympy.combinatorics.fp_groups import FpGroup

        >>> H = PermutationGroup(Permutation(0, 2), Permutation (1, 5))
        >>> K = PermutationGroup(Permutation(5)(0, 2))
        >>> F = free_group("x_0 x_1")[0]
        >>> gens = F.generators
        >>> phi = homomorphism(F, H, F.generators, H.generators)
        >>> rels_k = [gens[0]**2] # relators for presentation of K
        >>> z= Permutation(1, 5)
        >>> check, rels_h = H._verify(K, phi, z, 1)
        >>> check
        True
        >>> rels = rels_k + rels_h
        >>> G = FpGroup(F, rels) # presentation of H
        >>> G.order() == H.order()
        True

        See also
        ========

        strong_presentation, presentation, stabilizer

        r   r   Tr  rP  NF)r9  r  r8   rj  r   invertr   r4  r  r=   ru   rR  r   )r   r   phir  r  r9  r  K_betagammasr  r   r  r)  r   betastransversalrT  rE   r  r   r   relsr   k_gensr   new_relr   r   s                               r/   _verifyzPermutationGroup._verify   s   \ ae}d# u=!uV\\!_-=>(./c!f/
/ 	#C& c"	#
 cjj4dCJJq"u<MN''D'9 	ADAq#!,T!23::a=!@A	A
 $$QWWT]35zCJ& 
E>aA~Q)4U);CJJqM)IA$%$7$7$7$F NDAq 31<Q

11MAN !&AGGAJ 7
 5zCJ&  	)A\\!_//F )%a.**1t*<dd 4A%cjjm3G4!+a.""447|'..td.CD  8A%cjjmR&77G8$&KK()	)&  
	%E!%(A6{577KR7OOGw<D#**4$*?  4!#**Q-"334d"G$
	% Tz >/V " ' $;&'  #d{"#s/   !L5$L:,L?(M?MMM('M(c                    ddl m}m} ddlm} ddlm}m}m} | j                  dd }| j                  dd }| j                  dd }	t        t        |            D 
cg c]  }
d|
z  	 }}
 |dj                  |            d   } ||| |j                  |      }t!        | j"                        }|r|	j%                         }|}|j%                         }|j                  D cg c]	  }||vs| }}|j'                         dk(  r?|j%                         }|j                  d	   |j'                         z  g}|g}t!        |      }|rf|j%                         }|gz   }t!        |      }|j)                  |      }|j)                  |      }||k(  r||v r|j+                  |      }|}nC|j-                  |||z        }|j+                  |      |j+                  |      d	z  z  }||d	z  z  }|j/                  |d
      D ]  }||j+                  |      d	z  z  } |g}nlt        |      dk(  r|j1                  ||||      \  }}nE|j3                  ||      \  }}|r- |||      }|j4                  j6                  } |j6                  }!t9               }"t        |       D ]  }
|"t9        |
|
|!z         z  }" |j:                  }#|#D ci c]  }|||"z  |#|   z  |"z   }$}| j                  dt        |j                          D ]  }||$|<   	 t!        t=        |$j?                                     }% || |%|$      }&t!        |j                  D cg c]
  } |&|       c}      }'|%j1                  |'|&jA                  |       |&|      |!      \  }}D ]  }(|(vs|jC                  |(        |}|rf|r ||      }) ||)      S c c}
w c c}w c c}w c c}w )a3  
        Return a strong finite presentation of group. The generators
        of the returned group are in the same order as the strong
        generators of group.

        The algorithm is based on Sims' Verify algorithm described
        in [1], Chapter 6.

        Examples
        ========

        >>> from sympy.combinatorics.named_groups import DihedralGroup
        >>> P = DihedralGroup(4)
        >>> G = P.strong_presentation()
        >>> P.order() == G.order()
        True

        See Also
        ========

        presentation, _verify

        r   FpGroupsimplify_presentation
free_group)r  homomorphismGroupHomomorphismNx_%d, r7   r   TrP  )"sympy.combinatorics.fp_groupsr  r  sympy.combinatorics.free_groupsr  r  r  r  r  r   r   r   r<   r=   joinru   r&   r   r:   r   r9  r  r  rR  r  r  codomainr5   r   imagesr8   r   composer   )*rd   r  r  r  r  r  r  r   stabsr   rD   gen_symsFr  r   r  r   rE   new_gensr  r  intermediate_gensK_sr9  orbit_krelr   r   new_relssuccesscheckr  r\  r  r   t_imgr  K_s_actrU  K_actr   groups*                                             r/   strong_presentationz$PermutationGroup.strong_presentation  s   0	C>	L 	L &&q)&&q)yy| ).c+.>(?@1VAX@@tyy*+A.1dALL+>T]]+HHJEA		A#$<<>a1A:>H>wwyA~LLNR(!'')34%&C!$%67 LLN%&C*;$;!&'89		%(''%. e#Av!jjm KKuQw7!jjmCJJqM2,== Bw000E 4!#**Q-"334 #uH\Q& ),AsAu(E%GX $'#4#4Q#>LE5
 /sE:JJ--JJ (M!&q 5AQ!!44A5 !" >C!C!QqSq\!^"3!C!C!%!1!12GC4G3G!H *A()F1I*"243H"I-dGVD 01M1!A$1M N,3OOE199S>STUVSWYZ,[)! 'A}A'   \ 4 $U++i A ?x "D 2Ns   O!	O+OOOc                 (  # ddl m#m} ddlm} ddlm} ddlm} | j                  r| j                  S #fd}| j                  }t        |      }|dk(  r;|d   j                         }	|	dk(  r |g       d   S  |d      \  }
} #|
||	z  g      S | j                         d	kD  r| j                  d|dz   d
z   }ng }t        |      }|j                         }t        |j                        }| j                  |      }t        |      }t!        t        |            D cg c]  }d|z  	 }} |dj#                  |            d   }
t!        |      D cg c]  }|
j                  |    }} |||
|j                  |d      } ||j$                        } #|
|      } ||| |j                  |      } ||g       }t!        |      D cg c]  }dgd
|z  z   c}|_        dg|z  }|j(                  |d<   t!        d
|z        D ]  }d|j&                  d   |<    d}t+        t!        |      t!        d
|z              D ]r  \  }}||   |   }||k(  s|j                  |d
z     d|d
z  z  z  }||   |z  ||<   ||j&                  |   |<   ||j&                  |   |d|d
z  z  z   <   |dz  }||k(  sr n t-        t!        |            |_        dx}}|j1                         s|j&                  |   |   ||   |   k(  r4|dz   d
|z  z  }|dk(  r|dz   |z  }|j&                  |   |   ||   |   k(  r4|j                  |d
z     d|d
z  z  z  }||   |z  |||   |      dz  z  } ||      } |j(                  }!|j3                  | d      D ]  }"|!|j5                  |"      dz  z  }! ||!z  } |||g      }|j7                  d|       |j9                  g d||d      }|j1                         s ||      | _	        | j                  S c c}w c c}w c c}w )zz
        Return an `FpGroup` presentation of the group.

        The algorithm is described in [1], Chapter 6.1.

        r   r  )
CosetTabler  )r  c                     t        |       r@|j                  | j                          | j                  t	        t        |                  S  | |      S r*   )r+   r   relatorsr  r8   rt   )rA  r  r  s     r/   _factor_group_by_relsz<PermutationGroup.presentation.<locals>._factor_group_by_rels   sC    !W%AJJ'q||T#d)_==1d##rf   r7   r   r  r   r  r  F)r  Nr   TrP  r  )strategydraft
max_cosets
incomplete)r  r  r  sympy.combinatorics.coset_tabler  r  r  r  r  rb   ru   r=   r   r&   presentationr  r<   r  r  r  r   r   r8   r   is_completerR  r  scan_and_fillcoset_enumeration)$rd   eliminate_gensr  r  r  r  r  r   len_gr   r  r   	half_gensr   H_plen_hr  r   rD   r  r  r  r  G_pr   C_pr  r   r  r  r   r  r   rh  rT  r  s$                                      @r/   r  zPermutationGroup.presentation  sS   	C>>B  (((	$ D	A:GMMOEz!"~a((c?DAq1q%xj))::<"57Q,7IIY'nnCNN#QF(-c$i(891VAX99tyy*+A. ,1<8a!,,q/88auE a dCNND9b!/4Qx8!dVQuW%8	 fQhA qw 	 ACIIaLO	  a%%.9 		HE1U8A;Du}nnQT*bAE];$/$6s$:D!&*		% #5:		$R1q5M 12
A:		 U1Xq//#))D/!$$
2Uqw'6 1H>D ))D/!$$
2 ..A&"A7C!$'+K$
,CR,GGGW:D,,C(((= *!((1+r/)*ckG (gY7Ca)'']&)aD ( JC' //#, !6c :$$$A : 9 9s   PP
Pc                 2   ddl m} | j                  st        d      | j	                         }g }g }g }|j                  |d          |j                          t        t        |      dz
        D ]  }||   }||dz      j                  D ]  }||vst        |g|j                  z         }|j                  d|       |j                  d|       |d   j                         }	|d   j                         }
|j                  d|	|
z            ||||d      S )aU  
        Return the PolycyclicGroup instance with below parameters:

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

        * pc_sequence : Polycyclic sequence is formed by collecting all
          the missing generators between the adjacent groups in the
          derived series of given permutation group.

        * pc_series : Polycyclic series is formed by adding all the missing
          generators of ``der[i+1]`` in ``der[i]``, where ``der`` represents
          the derived series.

        * relative_order : A list, computed by the ratio of adjacent groups in
          pc_series.

        r   )PolycyclicGroupzThe group must be solvabler   r7   N)	collector)sympy.combinatorics.pc_groupsr  r  r   r   r   rG  r<   r=   ru   r&   insertr   )rd   r  r   	pc_seriespc_sequencerelative_orderrD   r   rE   G1rr  s              r/   polycyclic_groupz!PermutationGroup.polycyclic_group  s   & 	B!!9::!!#	R!s3xz" 
	7AAA1X(( 7A:(!q||);<A$$Q*&&q!,"1++-B"1++-B"))!R2X67
	7 {I~QUVVrf   r*   )FNNN)F)rt  F)Tr  )g?N)r  tuples)   2   N)NN)NNF)NNr  N)NNNN)c__name__
__module____qualname____doc__is_groupr@   re   rj   ro   rr   r{   r   r   r   r   propertyr   r   r   r   r   r   r  r
  r  r  r  rG  rN  rR  rX  r_  r5   r   r   r   re  rc  rw  rv  ru   rn   r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r0  r  r   r  r  r  r@  r9  r  r4  r   r   r   r  r  classmethodr   r(  r,  r1  r6  r8  r   r   r   r   r2  rX  r   r  r   r_  r5  r|  r  r  r  r  r  r  r  r  r   rf   r/   r&   r&      s   ^~ H!% 32!%F# "%%N)&V:?x/b)V    D ;@IMD)L " "> .! .!` " "@HT=~6*X$Lu?n-^Yv'R-^0  @ 1 1  "/b-^3Oj8(tDL     <;|    &  @HTP06$L;z +& +&Z,\=~Qf #% #%J:?x    $1f    $%N # #JWJr9x>cBJ$CL&6PO:7 1f+& 7: 7:t 7: 7:r 	 	 T Tl ^! ^!@3&j1f+,'\,@%2w"r FH*.B!H/bM6 !! !!F
 HL&*{Fz 0- 0-d$(LhTE#N;ztlx,tm%^*Wrf   r&   c           	      (   t        |d      s|g}|D cg c]  }|j                   }}t        |      dk(  s|dk(  rQ|}dg| z  }|D ]  }d||<   	 |D ]-  }	|D ]&  }
|
|	   }||   dk(  s|j                  |       d||<   ( / t	        |      S |dk(  rmt        |      }|g}|h}|D ]L  }	|D ]E  }
t        |	D cg c]  }|
|   	 c}      }||vs$|j                  |       |j                  |       G N t	        |      S |dk(  r{t        |      }|g}|h}|D ]L  }	|D ]E  }
t        |	D cg c]  }|
|   	 c}      }||vs$|j                  |       |j                  |       G N |D ch c]  }t        |       c}S yc c}w c c}w c c}w c c}w )	a  Compute the orbit of alpha `\{g(\alpha) | g \in G\}` as a set.

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

    The time complexity of the algorithm used here is `O(|Orb|*r)` where
    `|Orb|` is the size of the orbit and ``r`` is the number of generators of
    the group. For a more detailed analysis, see [1], p.78, [2], pp. 19-21.
    Here alpha can be a single point, or a list of points.

    If alpha is a single point, the ordinary orbit is computed.
    if alpha is a list of points, there are three available options:

    'union' - computes the union of the orbits of the points in the list
    'tuples' - computes the orbit of the list interpreted as an ordered
    tuple under the group action ( i.e., g((1, 2, 3)) = (g(1), g(2), g(3)) )
    'sets' - computes the orbit of the list interpreted as a sets

    Examples
    ========

    >>> from sympy.combinatorics import Permutation, PermutationGroup
    >>> from sympy.combinatorics.perm_groups import _orbit
    >>> a = Permutation([1, 2, 0, 4, 5, 6, 3])
    >>> G = PermutationGroup([a])
    >>> _orbit(G.degree, G.generators, 0)
    {0, 1, 2}
    >>> _orbit(G.degree, G.generators, [0, 4], 'union')
    {0, 1, 2, 3, 4, 5, 6}

    See Also
    ========

    orbit, orbit_transversal

    rj   r7   r  FTr  setsN)r/  r   r=   r   rt   rj  rk  	frozenset)r5   ru   r  r	  r   r   r  rZ  r   r   r   r   s               r/   r   r     s   J 5-(#-.aAMM.D.
5zQ&G+wv~ 	BDH	 	&A &1v:&JJt$!%DJ	&	& 3x	8	egw 	#A #a0c!f01t#JJt$HHTN	#	# 3x	6	% gw 	#A # !!4Q#a&!45t#JJt$HHTN	#	# #&&Qa&& 
1 /& 1 "5 's   F 6F(F
*Fc                     g }t        t        |             }t        |      }|r?|d   }t        | ||      }|j	                  |       ||z  }|D cg c]	  }||vs| }}|r?|S c c}w )a  Compute the orbits of G.

    If ``rep=False`` it returns a list of sets else it returns a list of
    representatives of the orbits

    Examples
    ========

    >>> from sympy.combinatorics import Permutation
    >>> from sympy.combinatorics.perm_groups import _orbits
    >>> a = Permutation([0, 2, 1])
    >>> b = Permutation([1, 0, 2])
    >>> _orbits(a.size, [a, b])
    [{0, 1, 2}]
    r   )r8   r<   rt   r   r   )r5   ru   rK  sorted_IrK  rD   r  s          r/   r  r    sy    " DE&M"HHA
QKVZ+C	S'8!1C<A88  K 9s   	A%A%c           	      F   |t        t        |             fg}|g i}dg| z  }d||<   |D 	cg c]  }	|	j                   }
}	|D ]Y  \  }	}||	   }|
D ]J  }||	   }||   dk(  s|
j                  |      g|z   ||<   |j	                  |t        ||      f       d||<   L [ |r)|s|D 	cg c]  \  }	}|	t        |      f }}	}|s|S ||fS |r|D cg c]  \  }}|	 }}}|s|S ||fS |D cg c]  \  }}t        |       }}}|s|S ||fS c c}	w c c}}	w c c}}w c c}}w )a  Computes a transversal for the orbit of ``alpha`` as a set.

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

    generators   generators of the group ``G``

    For a permutation group ``G``, a transversal for the orbit
    `Orb = \{g(\alpha) | g \in G\}` is a set
    `\{g_\beta | g_\beta(\alpha) = \beta\}` for `\beta \in Orb`.
    Note that there may be more than one possible transversal.
    If ``pairs`` is set to ``True``, it returns the list of pairs
    `(\beta, g_\beta)`. For a proof of correctness, see [1], p.79

    if ``af`` is ``True``, the transversal elements are given in
    array form.

    If `slp` is `True`, a dictionary `{beta: slp_beta}` is returned
    for `\beta \in Orb` where `slp_beta` is a list of indices of the
    generators in `generators` s.t. if `slp_beta = [i_1 \dots i_n]`
    `g_\beta = generators[i_n] \times \dots \times generators[i_1]`.

    Examples
    ========

    >>> from sympy.combinatorics.named_groups import DihedralGroup
    >>> from sympy.combinatorics.perm_groups import _orbit_transversal
    >>> G = DihedralGroup(6)
    >>> _orbit_transversal(G.degree, G.generators, 0, False)
    [(5), (0 1 2 3 4 5), (0 5)(1 4)(2 3), (0 2 4)(1 3 5), (5)(0 4)(1 3), (0 3)(1 4)(2 5)]
    FT)r8   r<   r   r   r   r   r>   )r5   ru   r  r  r[  rS  rM  r@  rZ  r   r   pxpx_slpr   r   r   r   s                    r/   r  r    so   B $uV}%
&	'Br{H76>DDK#-.aAMM.D. "2! 	"Cq6DDzU""&**S/!2V!;		4#r!234!T
	"" .01da1gaj/1B1I8|	DAqaI8|!#	$A'!*	$B	$	x<3 / 2  
 
%s   D'DD,Dc                    |g}|t        t        |             i}|t        t        |             i}dg| z  }d||<   |D cg c]  }|j                   }}g }	|D ]w  }
|D ]p  }||
   }||   du r9t        |||
         }|j	                  |       |||<   t        |      ||<   d||<   Ht        ||   |||
         }||	vs`|	j	                  |       r y |	D cg c]  }t        |       c}S c c}w c c}w )aO  Return the stabilizer subgroup of ``alpha``.

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

    The stabilizer of `\alpha` is the group `G_\alpha =
    \{g \in G | g(\alpha) = \alpha\}`.
    For a proof of correctness, see [1], p.79.

    degree :       degree of G
    generators :   generators of G

    Examples
    ========

    >>> from sympy.combinatorics.perm_groups import _stabilizer
    >>> from sympy.combinatorics.named_groups import DihedralGroup
    >>> G = DihedralGroup(6)
    >>> _stabilizer(G.degree, G.generators, 5)
    [(5)(0 4)(1 3), (5)]

    See Also
    ========

    orbit

    FT)r8   r<   r   r   r   r
   r   r>   )r5   ru   r  r  r  	table_invrZ  r   r   r0  r   r   r   gen_temprR  s                  r/   r.  r.  X  s   8 'CDv'(EU6]+,I76>DDK#-.aAMM.D.I 3 	3Cq6DDzU"#Cq2

4 &d",X"6	$!T
(4#uQxHy0$$\2	33 !**1GAJ** / +s   C+C0c                   H    e Zd ZdZd Zd Zd Zd Zed        Z	ed        Z
y)	r  zM
    The class defining the lazy form of SymmetricGroup.

    deg : int

    c                 H    t        |      }t        j                  | |      }|S r*   )r   r   r@   )rA   r   objs      r/   r@   z!SymmetricPermutationGroup.__new__  s     smmmC%
rf   c                 :    | j                   d   | _        d | _        y rG   )rB   _degrI   rc   s      r/   re   z"SymmetricPermutationGroup.__init__  s    IIaL	rf   c                     t        |t              st        dt        |      z        |j                  | j
                  k(  S )a"  Return ``True`` if *i* is contained in SymmetricPermutationGroup.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, SymmetricPermutationGroup
        >>> G = SymmetricPermutationGroup(4)
        >>> Permutation(1, 2, 3) in G
        True

        z[A SymmetricPermutationGroup contains only Permutations as elements, not elements of type %s)r+   r   rl   rm   r3   r5   ri   s     r/   ro   z&SymmetricPermutationGroup.__contains__  sC     ![) @BFq'J K Kvv$$rf   c                     | j                   | j                   S | j                  }t        |      | _         | j                   S )z
        Return the order of the SymmetricPermutationGroup.

        Examples
        ========

        >>> from sympy.combinatorics import SymmetricPermutationGroup
        >>> G = SymmetricPermutationGroup(4)
        >>> G.order()
        24
        )rI   r  r   )rd   r   s     r/   r   zSymmetricPermutationGroup.order  s6     ;;";;IIl{{rf   c                     | j                   S )z
        Return the degree of the SymmetricPermutationGroup.

        Examples
        ========

        >>> from sympy.combinatorics import SymmetricPermutationGroup
        >>> G = SymmetricPermutationGroup(4)
        >>> G.degree
        4

        )r  rq   s    r/   r5   z SymmetricPermutationGroup.degree  s     yyrf   c                 P    t        t        t        | j                                    S )a  
        Return the identity element of the SymmetricPermutationGroup.

        Examples
        ========

        >>> from sympy.combinatorics import SymmetricPermutationGroup
        >>> G = SymmetricPermutationGroup(4)
        >>> G.identity()
        (3)

        )r>   r8   r<   r  rq   s    r/   r   z"SymmetricPermutationGroup.identity  s     tE$)),-..rf   N)r  r  r   r  r@   re   ro   r   r  r5   r   r   rf   r/   r  r    sC    
%"$   / /rf   r  c                   D    e Zd ZdZddZd Zed        Zed        Zd Z	y)	r   a  A left coset of a permutation group with respect to an element.

    Parameters
    ==========

    g : Permutation

    H : PermutationGroup

    dir : "+" or "-", If not specified by default it will be "+"
        here ``dir`` specified the type of coset "+" represent the
        right coset and "-" represent the left coset.

    G : PermutationGroup, optional
        The group which contains *H* as its subgroup and *g* as its
        element.

        If not specified, it would automatically become a symmetric
        group ``SymmetricPermutationGroup(g.size)`` and
        ``SymmetricPermutationGroup(H.degree)`` if ``g.size`` and ``H.degree``
        are matching.``SymmetricPermutationGroup`` is a lazy form of SymmetricGroup
        used for representation purpose.

    Nc                    t        |      }t        |t              st        t        |      }t        |t              st        |rt        |      }t        |t        t
        f      st        |j                  |      st        dj                  ||            ||vrht        dj                  ||            |j                  }|j                  }||k7  rt        dj                  ||            t        |j                        }t        |t              rt        |      }n't        |t              st        dt        |      z        t        |      dvrt        d|z        t        j                   | ||||      }|S )Nz{} must be a subgroup of {}.z{} must be an element of {}.z]The size of the permutation {} and the degree of the permutation group {} should be matching z0dir must be of type basestring or Symbol, not %s)r}   -z$dir must be one of '+' or '-' not %s)r   r+   r   r   r&   r  r   r   r  r3   r5   strr   rl   rm   r   r@   )rA   rE   r   rA  r~   g_sizeh_degreer  s           r/   r@   zCoset.__new__  sZ   QK![)%%QK!-.%%=Aa"24M!NO))==# !?!F!Fq!!LMMz !?!F!Fq!!LMMVVFxxH! CVAq\# # *!&&1Ac3+CC( %'+Cy1 2 2s8:%CcIJJmmCAq#.
rf   c                 ,    | j                   d   | _        y )N   )rB   _dirrc   s      r/   re   zCoset.__init__!  s    IIaL	rf   c                 2    t        | j                        dk(  S )aw  
        Check if the coset is left coset that is ``gH``.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup, Coset
        >>> a = Permutation(1, 2)
        >>> b = Permutation(0, 1)
        >>> G = PermutationGroup([a, b])
        >>> cst = Coset(a, G, dir="-")
        >>> cst.is_left_coset
        True

        r  r  r!  rq   s    r/   is_left_cosetzCoset.is_left_coset$      " 499~$$rf   c                 2    t        | j                        dk(  S )ay  
        Check if the coset is right coset that is ``Hg``.

        Examples
        ========

        >>> from sympy.combinatorics import Permutation, PermutationGroup, Coset
        >>> a = Permutation(1, 2)
        >>> b = Permutation(0, 1)
        >>> G = PermutationGroup([a, b])
        >>> cst = Coset(a, G, dir="+")
        >>> cst.is_right_coset
        True

        r}   r#  rq   s    r/   is_right_cosetzCoset.is_right_coset7  r%  rf   c                    | j                   d   }| j                   d   }g }t        | j                        dk(  r'|j                  D ]  }|j	                  ||z          |S |j                  D ]  }|j	                  ||z          |S )zG
        Return all the elements of coset in the form of list.
        r   r7   r}   )rB   r  r!  r   r   )rd   rE   r   cstr   s        r/   as_listzCoset.as_listJ  s     IIaLIIaLtyy>S ZZ  

1Q3 
 
 ZZ  

1Q3 
rf   )Nr}   )
r  r  r   r  r@   re   r  r$  r'  r*  r   rf   r/   r   r     s?    2#J! % %$ % %$rf   r   Nr  r  )<mathr   r  r   r   	itertoolsr   r   sympy.combinatoricsr    sympy.combinatorics.permutationsr	   r
   r   r   r   r   sympy.combinatorics.utilr   r   r   r   r   r   r   r   
sympy.corer   sympy.core.randomr   r   r   sympy.core.symbolr   sympy.core.sympifyr   (sympy.functions.combinatorial.factorialssympy.ntheoryr   r   sympy.ntheory.factor_r   r    sympy.ntheory.primetestr!   sympy.utilities.iterablesr"   r#   r$   rmul_with_afr   r>   r&   r   r  r  r.  r  r  r   r   rf   r/   <module>r:     s    3 3 $ ,) )    ; ; $ ' > - ; + D D


ONWu ONWd\J'Z<>B0+f 	Q/ Q/huE urf   