
    \hc                       S SK JrJrJr  S SKJrJrJrJrJ	r	J
r
JrJr  S SKJr  S SKJr  S SKJrJrJr  S SKJr  S SKJr  SQS	 jrSRS
 jrSSS jrS rSTS jrS rS rS rSUS jr SVS jr!SUS jr"S r#SWS jr$S r%SVS jr&S r'S r(S r)S r*S r+S r,SXS jr-S r.S  r/S! r0S" r1S# r2SXS$ jr3SXS% jr4SRS& jr5SXS' jr6S( r7SXS) jr8SYS* jr9SZS+ jr:S, r;S- r<S. r=SXS/ jr>S0 r?S1 r@S2 rASZS3 jrBS4 rCS5 rDSVS6 jrES7 rFS8 rGS[S9 jrH\4S: jrIS; rJS< rKSXS= jrLS> rMS? rNS\S@ jrOSA rP " SB SC5      rQ\R\S\Q44SD jrTSXSE jrU\" SFSGSHSI9SXSJ j5       rV\" SKSGSHSI9SL 5       rW\" SMSGSNSI9SO 5       rX\" SMSGSNSI9SP 5       rYg)]    )CounterdefaultdictOrderedDict)chaincombinationscombinations_with_replacementcycleislicepermutationsproductgroupby)r   )gt)multiset_partitions_taocplist_visitorMultisetPartitionTraverseras_int)
deprecatedNc                    ^ ^^ [        TT5      R                  [        T 5      5      u  mmnTT-
  S-  n[        UUU 4S j[	        U5       5       5      $ )aj  
Return True if the sequence is the same from left to right as it
is from right to left in the whole sequence (default) or in the
Python slice ``s[i: j]``; else False.

Examples
========

>>> from sympy.utilities.iterables import is_palindromic
>>> is_palindromic([1, 0, 1])
True
>>> is_palindromic('abcbb')
False
>>> is_palindromic('abcbb', 1)
False

Normal Python slicing is performed in place so there is no need to
create a slice of the sequence for testing:

>>> is_palindromic('abcbb', 1, -1)
True
>>> is_palindromic('abcbb', -4, -1)
True

See Also
========

sympy.ntheory.digits.is_palindromic: tests integers

   c              3   L   >#    U  H  nTTU-      TTS -
  U-
     :H  v   M     g7f   N ).0kijss     Q/var/www/auris/envauris/lib/python3.13/site-packages/sympy/utilities/iterables.py	<genexpr>!is_palindromic.<locals>.<genexpr>6   s*     :AqQx1QUQY<'   !$)sliceindiceslenallrange)r   r   r   _ms   ```  r    is_palindromicr+      sG    > Aqk!!#a&)GAq!	
Q
A:q:::    c           	      \  ^ SSK Jn  Ub#  U(       d  U $ US:  a  US-  nO[        SU-  5      eTc  S nOU4S jn/ nU  Hi  nU" U5      (       aH  [        US5      (       a  [	        Xc5      (       d  UR
                  nUR                  [        XaTS95        MX  UR                  U5        Mk     U$ )	a
  
Recursively denest iterable containers.

>>> from sympy import flatten

>>> flatten([1, 2, 3])
[1, 2, 3]
>>> flatten([1, 2, [3]])
[1, 2, 3]
>>> flatten([1, [2, 3], [4, 5]])
[1, 2, 3, 4, 5]
>>> flatten([1.0, 2, (1, None)])
[1.0, 2, 1, None]

If you want to denest only a specified number of levels of
nested containers, then set ``levels`` flag to the desired
number of levels::

>>> ls = [[(-2, -1), (1, 2)], [(0, 0)]]

>>> flatten(ls, levels=1)
[(-2, -1), (1, 2), (0, 0)]

If cls argument is specified, it will only flatten instances of that
class, for example:

>>> from sympy import Basic, S
>>> class MyOp(Basic):
...     pass
...
>>> flatten([MyOp(S(1), MyOp(S(2), S(3)))], cls=MyOp)
[1, 2, 3]

adapted from https://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks
r   )	NDimArrayr   z.expected non-negative number of levels, got %sc                 "    [        U [        5      $ N)is_sequencesetxs    r    	reducibleflatten.<locals>.reducibleh   s    q#&&r,   c                    > [        U T5      $ r0   )
isinstance)r4   clss    r    r5   r6   k   s    a%%r,   args)levelsr9   )	sympy.tensor.arrayr.   
ValueErrorhasattrr8   r:   extendflattenappend)iterabler;   r9   r.   r5   resultels     `    r    r@   r@   9   s    H -OaZaKF@6IK K {	'	& FR==r6"":b+D+DWWMM'"=>MM"  Mr,   c                    ^ ^ TS:  d  [        T 5      T-  (       a  [        ST-  5      e[        [        U U4S j[	        T5       5       6 5      $ )zqGroup ``iter`` into tuples of length ``n``. Raise an error if
the length of ``iter`` is not a multiple of ``n``.
r   z#iter length is not a multiple of %ic              3   4   >#    U  H  nTUS T2   v   M     g 7fr0   r   )r   r   iterns     r    r!   unflatten.<locals>.<genexpr>   s     3(Qd14a4j(s   )r&   r=   listzipr(   )rG   rH   s   ``r    	unflattenrL   {   sA     	1uD	A>BCC3%(3455r,   c                 &   [        [        U5      5      n[        [        U 5      U5      u  p4US:  d  U(       a  [	        S5      eSn[        U5      nS/U-  n[        [        U5      5       H  n/ n	U H~  n
[        U
[        5      (       a  U	R                  XXZ-    5        XZ-  nM3  [        [        U
5      5      n[        U
5      nU	R                  U" [        XXS-    U
5      S   5      5        XS-  nM     U" U	5      Xx'   M     [        U 5      " U5      $ )aJ  Reshape the sequence according to the template in ``how``.

Examples
========

>>> from sympy.utilities import reshape
>>> seq = list(range(1, 9))

>>> reshape(seq, [4]) # lists of 4
[[1, 2, 3, 4], [5, 6, 7, 8]]

>>> reshape(seq, (4,)) # tuples of 4
[(1, 2, 3, 4), (5, 6, 7, 8)]

>>> reshape(seq, (2, 2)) # tuples of 4
[(1, 2, 3, 4), (5, 6, 7, 8)]

>>> reshape(seq, (2, [2])) # (i, i, [i, i])
[(1, 2, [3, 4]), (5, 6, [7, 8])]

>>> reshape(seq, ((2,), [2])) # etc....
[((1, 2), [3, 4]), ((5, 6), [7, 8])]

>>> reshape(seq, (1, [2], 1))
[(1, [2, 3], 4), (5, [6, 7], 8)]

>>> reshape(tuple(seq), ([[1], 1, (2,)],))
(([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],))

>>> reshape(tuple(seq), ([1], 1, (2,)))
(([1], 2, (3, 4)), ([5], 6, (7, 8)))

>>> reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)])
[[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]]

r   zLtemplate must sum to positive number that divides the length of the sequenceN)sumr@   divmodr&   r=   typer(   r8   intr?   rA   reshape)seqhowr*   rH   remr   	containerrvr   _rvhihi_types               r    rR   rR      s    J 	GCLACHa FA1u 2 3 	3	AS	I
B3r7^B"c""

3!&>*$r(

773!%="#=a#@AB  #  9R=r,   c           
          U(       a)  [        U 5       VVs/ s H  u  p#[        U5      PM     snn$ [        U 5       VVs/ s H  u  pCU[        [        U5      5      4PM     snn$ s  snnf s  snnf )aa  
Splits a sequence into a list of lists of equal, adjacent elements.

Examples
========

>>> from sympy import group

>>> group([1, 1, 1, 2, 2, 3])
[[1, 1, 1], [2, 2], [3]]
>>> group([1, 1, 1, 2, 2, 3], multiple=False)
[(1, 3), (2, 2), (3, 1)]
>>> group([1, 1, 3, 2, 2, 1], multiple=False)
[(1, 2), (3, 1), (2, 2), (1, 1)]

See Also
========

multiset

)r   rJ   r&   )rS   multipler)   gr   s        r    groupr^      sV    , &-cl3ldaal33*1#,7,$!QDG,77 47s
   A%"A+c              #     ^	#    [        U 5      n[        U5      n/ n/ n[        5       m	U	4S jnSnU" X$5        U" X55        U[        U5      [        U5      -   ::  ak  [        U[        U5      -
  S-   [        U5      5       H  nXGU-
     XX   4v   M     US-  nU" X$5        U" X55        U[        U5      [        U5      -   ::  a  Mj  gg7f)z4Cartesian product of two possibly infinite iterablesc                 L   > [        U T5      nUTLa  UR                  U5        g g r0   )nextrA   )itelemsesentinels      r    rA   _iproduct2.<locals>.append   s'    XHLLO r,   r   r   N)rG   objectr&   r(   )
	iterable1	iterable2it1it2elems1elems2rA   rH   r*   re   s
            @r    
_iproduct2rn      s      y/C
y/CFFxH
 	
A
3
3
s6{S[(
(qV}QF4AA#;	** 5	Qss s6{S[(
(s   C CCc               '     #    [        U 5      S:X  a  Sv   g[        U 5      S:X  a  U S    H  nU4v   M
     g[        U 5      S:X  a  [        U 6  Sh  vN   gU S   U SS p2[        U[        U6 5       H  u  pEU4U-   v   M     g N27f)an  
Cartesian product of iterables.

Generator of the Cartesian product of iterables. This is analogous to
itertools.product except that it works with infinite iterables and will
yield any item from the infinite product eventually.

Examples
========

>>> from sympy.utilities.iterables import iproduct
>>> sorted(iproduct([1,2], [3,4]))
[(1, 3), (1, 4), (2, 3), (2, 4)]

With an infinite iterator:

>>> from sympy import S
>>> (3,) in iproduct(S.Integers)
True
>>> (3, 4) in iproduct(S.Integers, S.Integers)
True

.. seealso::

   `itertools.product
   <https://docs.python.org/3/library/itertools.html#itertools.product>`_
r   r   Nr   r   )r&   rn   iproduct)	iterablesrd   firstothersefeos         r    rp   rp      s     8 9~	Y1	1A$J 	Y1	y)))!!imv &(9:FB%"* ; 	*s   ABB3Bc                 F    [        [        U 5      R                  5       5      $ )a  Return the hashable sequence in multiset form with values being the
multiplicity of the item in the sequence.

Examples
========

>>> from sympy.utilities.iterables import multiset
>>> multiset('mississippi')
{'i': 4, 'm': 1, 'p': 2, 's': 4}

See Also
========

group

)dictr   items)rS   s    r    multisetry      s    " ""$%%r,   c                 .  ^  T S:  a  [        S5      e[        T 5      m Uc  SnOI [        U5      nT R                  5       U:  a(  [        SR                  T R                  5       5      5      e U(       dP  US:  a6  [	        T 5      SS R                  US5       Vs/ s H  o3S:X  a  S	OSPM     sn$ [        [        S5      T S
S9$ US:  a  [	        T 5      SS R                  US5      $ U 4S j[        ST -  5       5       $ ! [          a    Sn Nf = fs  snf )a  Return a list of length ``bits`` corresponding to the binary value
of ``n`` with small bits to the right (last). If bits is omitted, the
length will be the number required to represent ``n``. If the bits are
desired in reversed order, use the ``[::-1]`` slice of the returned list.

If a sequence of all bits-length lists starting from ``[0, 0,..., 0]``
through ``[1, 1, ..., 1]`` are desired, pass a non-integer for bits, e.g.
``'all'``.

If the bit *string* is desired pass ``str=True``.

Examples
========

>>> from sympy.utilities.iterables import ibin
>>> ibin(2)
[1, 0]
>>> ibin(2, 4)
[0, 0, 1, 0]

If all lists corresponding to 0 to 2**n - 1, pass a non-integer
for bits:

>>> bits = 2
>>> for i in ibin(2, 'all'):
...     print(i)
(0, 0)
(0, 1)
(1, 0)
(1, 1)

If a bit string is desired of a given length, use str=True:

>>> n = 123
>>> bits = 10
>>> ibin(n, bits, str=True)
'0001111011'
>>> ibin(n, bits, str=True)[::-1]  # small bits left
'1101111000'
>>> list(ibin(3, 'all', str=True))
['000', '001', '010', '011', '100', '101', '110', '111']

r   z negative numbers are not allowedNz`bits` must be >= {}r   01r   T)
repetitionc              3   `   >#    U  H#  n[        U5      S S R                  TS5      v   M%     g7f)r   Nr|   )binrjust)r   r   rH   s     r    r!   ibin.<locals>.<genexpr>{  s+     BkCF12J$$Q,,ks   +.)r=   r   
bit_lengthformatr   r   
variationsr(   )rH   bitsstrr   s   `   r    ibinr   6  s   X 	1u;<<q	A|	C$<D ||~$ *11!,,.AC C % 1925a&*2B2B42MN2MQcAq(2MNNeAhd;;19q6!":##D#..BeAqDkBB!  	D	 Os   D  D DDc                     U(       d0  [        U 5      n [        U 5      U:  a  [        S5      $ [        X5      $ US:X  a  [        S5      $ [	        XS9$ )a"  Returns an iterator over the n-sized variations of ``seq`` (size N).
``repetition`` controls whether items in ``seq`` can appear more than once;

Examples
========

``variations(seq, n)`` will return `\frac{N!}{(N - n)!}` permutations without
repetition of ``seq``'s elements:

    >>> from sympy import variations
    >>> list(variations([1, 2], 2))
    [(1, 2), (2, 1)]

``variations(seq, n, True)`` will return the `N^n` permutations obtained
by allowing repetition of elements:

    >>> list(variations([1, 2], 2, repetition=True))
    [(1, 1), (1, 2), (2, 1), (2, 2)]

If you ask for more items than are in the set you get the empty set unless
you allow repetitions:

    >>> list(variations([0, 1], 3, repetition=False))
    []
    >>> list(variations([0, 1], 3, repetition=True))[:4]
    [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1)]

.. seealso::

   `itertools.permutations
   <https://docs.python.org/3/library/itertools.html#itertools.permutations>`_,
   `itertools.product
   <https://docs.python.org/3/library/itertools.html#itertools.product>`_
r   r   )r   )repeat)tupler&   rG   r   r   )rS   rH   r~   s      r    r   r   ~  sL    F Cjs8a<8OC##6;3))r,   c                 *  ^  Ucq  U(       d5  [         R                  " U 4S j[        [        T 5      S-   5       5       5      $ [         R                  " U 4S j[        [        T 5      S-   5       5       5      $ U(       d  [	        T U5      $ [        T U5      $ )a  Generates all `k`-subsets (combinations) from an `n`-element set, ``seq``.

A `k`-subset of an `n`-element set is any subset of length exactly `k`. The
number of `k`-subsets of an `n`-element set is given by ``binomial(n, k)``,
whereas there are `2^n` subsets all together. If `k` is ``None`` then all
`2^n` subsets will be returned from shortest to longest.

Examples
========

>>> from sympy import subsets

``subsets(seq, k)`` will return the
`\frac{n!}{k!(n - k)!}` `k`-subsets (combinations)
without repetition, i.e. once an item has been removed, it can no
longer be "taken":

    >>> list(subsets([1, 2], 2))
    [(1, 2)]
    >>> list(subsets([1, 2]))
    [(), (1,), (2,), (1, 2)]
    >>> list(subsets([1, 2, 3], 2))
    [(1, 2), (1, 3), (2, 3)]


``subsets(seq, k, repetition=True)`` will return the
`\frac{(n - 1 + k)!}{k!(n - 1)!}`
combinations *with* repetition:

    >>> list(subsets([1, 2], 2, repetition=True))
    [(1, 1), (1, 2), (2, 2)]

If you ask for more items than are in the set you get the empty set unless
you allow repetitions:

    >>> list(subsets([0, 1], 3, repetition=False))
    []
    >>> list(subsets([0, 1], 3, repetition=True))
    [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)]

c              3   <   >#    U  H  n[        TU5      v   M     g 7fr0   r   r   r   rS   s     r    r!   subsets.<locals>.<genexpr>  s#      (F1DA )5S!(<(<1D   r   c              3   <   >#    U  H  n[        TU5      v   M     g 7fr0   )r   r   s     r    r!   r     s$      (F1DA )Fc1(M(M1Dr   )r   from_iterabler(   r&   r   r   )rS   r   r~   s   `  r    subsetsr     s    T 	y&& (F16s3x!|1D(F G G && (F16s3x!|1D(F G G Q''0a88r,   c              #   J   #    [        U5      nU  H  nX!;  d  M
  Uv   M     g7f)z
Only yield elements from `iterator` that do not occur in `exclude`.

Parameters
==========

iterator : iterable
    iterator to take elements from

exclude : iterable
    elements to exclude

Returns
=======

iterator : iterator
    filtered iterator
N)r2   )iteratorexcluder   s      r    filter_symbolsr     s%     & 'lGG s   #	#c              /      #    [        U=(       d    / 5      nUc  SSKJn  Un U < U< 3nU" U/UQ70 UD6nX;  a  Uv   US-  nM$  7f)a  
Generate an infinite stream of Symbols consisting of a prefix and
increasing subscripts provided that they do not occur in ``exclude``.

Parameters
==========

prefix : str, optional
    The prefix to use. By default, this function will generate symbols of
    the form "x0", "x1", etc.

cls : class, optional
    The class to use. By default, it uses ``Symbol``, but you can also use ``Wild``
    or ``Dummy``.

start : int, optional
    The start number.  By default, it is 0.

exclude : list, tuple, set of cls, optional
    Symbols to be excluded.

*args, **kwargs
    Additional positional and keyword arguments are passed to the *cls* class.

Returns
=======

sym : Symbol
    The subscripted symbols.
r   )Symbolr   )r2   
sympy.corer   )	prefixr9   startr   r:   assumptionsr   namer   s	            r    numbered_symbolsr     s^     > '-R G
{ 	&
'+t+{+G
 s   AAc                     SSK Jn  SSKnUR                  nU" 5       =Ul        n U " 5         X2l        UR	                  5       $ ! X2l        f = f)a  Return the printed output of func().

``func`` should be a function without arguments that produces output with
print statements.

>>> from sympy.utilities.iterables import capture
>>> from sympy import pprint
>>> from sympy.abc import x
>>> def foo():
...     print('hello world!')
...
>>> 'hello' in capture(foo) # foo, not foo()
True
>>> capture(lambda: pprint(2/x))
'2\n-\nx\n'

r   )StringION)ior   sysstdoutgetvalue)funcr   r   r   files        r    capturer   +  sE    $ ZZF 
"CJ
==? 
s   A Ac                    U(       d3  [        [        5      nU  H  nX1" U5         R                  U5        M     U$ / / 4=nu  pgU  H  n XQ" U5         R                  U5        M     Xv4$ ! [        [        4 a    [        S5      ef = f)a  
Sift the sequence, ``seq`` according to ``keyfunc``.

Returns
=======

When ``binary`` is ``False`` (default), the output is a dictionary
where elements of ``seq`` are stored in a list keyed to the value
of keyfunc for that element. If ``binary`` is True then a tuple
with lists ``T`` and ``F`` are returned where ``T`` is a list
containing elements of seq for which ``keyfunc`` was ``True`` and
``F`` containing those elements for which ``keyfunc`` was ``False``;
a ValueError is raised if the ``keyfunc`` is not binary.

Examples
========

>>> from sympy.utilities import sift
>>> from sympy.abc import x, y
>>> from sympy import sqrt, exp, pi, Tuple

>>> sift(range(5), lambda x: x % 2)
{0: [0, 2, 4], 1: [1, 3]}

sift() returns a defaultdict() object, so any key that has no matches will
give [].

>>> sift([x], lambda x: x.is_commutative)
{True: [x]}
>>> _[False]
[]

Sometimes you will not know how many keys you will get:

>>> sift([sqrt(x), exp(x), (y**x)**2],
...      lambda x: x.as_base_exp()[0])
{E: [exp(x)], x: [sqrt(x)], y: [y**(2*x)]}

Sometimes you expect the results to be binary; the
results can be unpacked by setting ``binary`` to True:

>>> sift(range(4), lambda x: x % 2, binary=True)
([1, 3], [0, 2])
>>> sift(Tuple(1, pi), lambda x: x.is_rational, binary=True)
([1], [pi])

A ValueError is raised if the predicate was not actually binary
(which is a good test for the logic where sifting is used and
binary results were expected):

>>> unknown = exp(1) - pi  # the rationality of this is unknown
>>> args = Tuple(1, pi, unknown)
>>> sift(args, lambda x: x.is_rational, binary=True)
Traceback (most recent call last):
...
ValueError: keyfunc gave non-binary output

The non-binary sifting shows that there were 3 keys generated:

>>> set(sift(args, lambda x: x.is_rational).keys())
{None, False, True}

If you need to sort the sifted items it might be better to use
``ordered`` which can economically apply multiple sort keys
to a sequence while sorting.

See Also
========

ordered

zkeyfunc gave non-binary output)r   rJ   rA   
IndexError	TypeErrorr=   )rS   keyfuncbinaryr*   r   siftFTs           r    r   r   I  s    R AgajM  # b&D41	?##A& 
 4K I& 	?=>>	?s   	A))Bc                 b    [        [        U5      U 5       VVs/ s H  u  p#UPM	     snn$ s  snnf )z+Return ``n`` items from ``iter`` iterator. )rK   r(   )rG   rH   r)   values       r    taker     s)    #&uQx#68#6xqU#6888s   +c                  >    0 nU  H  nUR                  U5        M     U$ )z-Merge dictionaries into a single dictionary. )update)dictsmergedrw   s      r    
dict_merger     s$    Fd  Mr,   c            	        ^ ^ [        T 5      (       d  / $ [        T 5      S:X  a  T S   $ Sm[        [        S T  5       5      5       H2  m[        UU 4S j[        [        T 5      5       5       5      (       a  M2    O   TS-  mT S   ST $ )aD  Return the subsequence that is a common start of sequences in ``seqs``.

>>> from sympy.utilities.iterables import common_prefix
>>> common_prefix(list(range(3)))
[0, 1, 2]
>>> common_prefix(list(range(3)), list(range(4)))
[0, 1, 2]
>>> common_prefix([1, 2, 3], [1, 2, 5])
[1, 2]
>>> common_prefix([1, 2, 3], [1, 3, 5])
[1]
r   r   c              3   8   #    U  H  n[        U5      v   M     g 7fr0   r&   r   r   s     r    r!    common_prefix.<locals>.<genexpr>  s     ,t!s1vvt   c              3   F   >#    U  H  nTU   T   TS    T   :H  v   M     g7fr   Nr   r   r   r   seqss     r    r!   r     (     F5E471:a+5E   !Nr'   r&   r(   minr   r   s   `@r    common_prefixr     s~     t99		TaAw	A3,t,,-FU3t95EFFF . 	
Q72A;r,   c            	      4  ^ ^ [        T 5      (       d  / $ [        T 5      S:X  a  T S   $ Sm[        S[        S T  5       5      * S-
  S5       H2  m[        UU 4S j[        [        T 5      5       5       5      (       a  M2    O   TS-  mTS:X  a  / $ T S   TS-   S $ )a>  Return the subsequence that is a common ending of sequences in ``seqs``.

>>> from sympy.utilities.iterables import common_suffix
>>> common_suffix(list(range(3)))
[0, 1, 2]
>>> common_suffix(list(range(3)), list(range(4)))
[]
>>> common_suffix([1, 2, 3], [9, 2, 3])
[2, 3]
>>> common_suffix([1, 2, 3], [9, 7, 3])
[3]
r   r   r{   c              3   8   #    U  H  n[        U5      v   M     g 7fr0   r   r   s     r    r!    common_suffix.<locals>.<genexpr>  s     1DqCFFDr   c              3   F   >#    U  H  nTU   T   TS    T   :H  v   M     g7fr   r   r   s     r    r!   r     r   r   Nr   r   s   `@r    common_suffixr     s     t99		TaAw	A21D111A5r:FU3t95EFFF ; 	
QBw	Awq1uvr,   c              #   Z   #    [        U 5      n[        U5       H  nU SUS-    v   M     g7f)z
Generate all prefixes of a sequence.

Examples
========

>>> from sympy.utilities.iterables import prefixes

>>> list(prefixes([1,2,3,4]))
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]

Nr   r&   r(   rS   rH   r   s      r    prefixesr     s.      	CA1X&1q5k s   )+c              #   ^   #    [        U 5      n[        U5       H  nXU-
  S-
  S v   M     g7f)z
Generate all postfixes of a sequence.

Examples
========

>>> from sympy.utilities.iterables import postfixes

>>> list(postfixes([1,2,3,4]))
[[4], [3, 4], [2, 3, 4], [1, 2, 3, 4]]

r   Nr   r   s      r    	postfixesr     s0      	CA1Xa%!)*o s   +-c                 0   U u  p#/ n[        U5      n[        U5      nUR                  S U 5       5        Uc  S n[        XQSS9nU(       a  UR	                  5       nUR                  U5        [        U5       H  u  pxXv:X  d  M  UR                  Xx45        U H  u  pX:X  d  M    M/     U" U5      n[        U5       H&  u  pU" U5      nX:  d  M  UR                  X5          Ml     UR                  U5        M     U(       a  M  U(       a  [        S5      eU$ )a)  
Topological sort of graph's vertices.

Parameters
==========

graph : tuple[list, list[tuple[T, T]]
    A tuple consisting of a list of vertices and a list of edges of
    a graph to be sorted topologically.

key : callable[T] (optional)
    Ordering key for vertices on the same level. By default the natural
    (e.g. lexicographic) ordering is used (in this case the base type
    must implement ordering relations).

Examples
========

Consider a graph::

    +---+     +---+     +---+
    | 7 |\    | 5 |     | 3 |
    +---+ \   +---+     +---+
      |   _\___/ ____   _/ |
      |  /  \___/    \ /   |
      V  V           V V   |
     +----+         +---+  |
     | 11 |         | 8 |  |
     +----+         +---+  |
      | | \____   ___/ _   |
      | \      \ /    / \  |
      V  \     V V   /  V  V
    +---+ \   +---+ |  +----+
    | 2 |  |  | 9 | |  | 10 |
    +---+  |  +---+ |  +----+
           \________/

where vertices are integers. This graph can be encoded using
elementary Python's data structures as follows::

    >>> V = [2, 3, 5, 7, 8, 9, 10, 11]
    >>> E = [(7, 11), (7, 8), (5, 11), (3, 8), (3, 10),
    ...      (11, 2), (11, 9), (11, 10), (8, 9)]

To compute a topological sort for graph ``(V, E)`` issue::

    >>> from sympy.utilities.iterables import topological_sort

    >>> topological_sort((V, E))
    [3, 5, 7, 8, 11, 2, 9, 10]

If specific tie breaking approach is needed, use ``key`` parameter::

    >>> topological_sort((V, E), key=lambda v: -v)
    [7, 5, 11, 3, 10, 8, 9, 2]

Only acyclic graphs can be sorted. If the input graph has a cycle,
then ``ValueError`` will be raised::

    >>> topological_sort((V, E + [(10, 7)]))
    Traceback (most recent call last):
    ...
    ValueError: cycle detected

References
==========

.. [1] https://en.wikipedia.org/wiki/Topological_sorting

c              3   *   #    U  H	  u  pUv   M     g 7fr0   r   )r   vus      r    r!   #topological_sort.<locals>.<genexpr>Z  s     (adaa   c                     U $ r0   r   )r   s    r    keytopological_sort.<locals>.key]  s    Lr,   T)r   reversezcycle detected)
r2   rJ   difference_updatesortedpoprA   remove	enumerateinsertr=   )graphr   VELSnoder   r   _u_vkvr   r   kss                  r    topological_sortr     s    N DA
AAAQA(a((
{	 	q4(A
uuw	GDAy! FBw   QB )! V7HHQN! !- # 	 !. 	)**r,   c                     U u  pU Vs0 s H  o3/ _M     nnU H  u  pVXE   R                  U5        M     [        X5      $ s  snf )a!  
Strongly connected components of a directed graph in reverse topological
order.


Parameters
==========

G : tuple[list, list[tuple[T, T]]
    A tuple consisting of a list of vertices and a list of edges of
    a graph whose strongly connected components are to be found.


Examples
========

Consider a directed graph (in dot notation)::

    digraph {
        A -> B
        A -> C
        B -> C
        C -> B
        B -> D
    }

.. graphviz::

    digraph {
        A -> B
        A -> C
        B -> C
        C -> B
        B -> D
    }

where vertices are the letters A, B, C and D. This graph can be encoded
using Python's elementary data structures as follows::

    >>> V = ['A', 'B', 'C', 'D']
    >>> E = [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'B'), ('B', 'D')]

The strongly connected components of this graph can be computed as

    >>> from sympy.utilities.iterables import strongly_connected_components

    >>> strongly_connected_components((V, E))
    [['D'], ['B', 'C'], ['A']]

This also gives the components in reverse topological order.

Since the subgraph containing B and C has a cycle they must be together in
a strongly connected component. A and D are connected to the rest of the
graph but not in a cyclic manner so they appear as their own strongly
connected components.


Notes
=====

The vertices of the graph must be hashable for the data structures used.
If the vertices are unhashable replace them with integer indices.

This function uses Tarjan's algorithm to compute the strongly connected
components in `O(|V|+|E|)` (linear) time.


References
==========

.. [1] https://en.wikipedia.org/wiki/Strongly_connected_component
.. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm


See Also
========

sympy.utilities.iterables.connected_components

)rA   _strongly_connected_components)Gr   r   viGmapv1v2s          r    strongly_connected_componentsr     sL    d DAQrFQD )!22  s   A c                 Z  ^^	^
^^^ 0 m0 m[        5       m/ m	/ m
[        5       nUU	UUU4S jnU	U
UUU4S jnU  Hn  nUT;   a  M  U" U5        T	(       d  M  T	S   u  pg[        Xr5      nXL a	  U" U5        O*UT;  a	  U" U5        OUT;   a  [        TU   TU   5      TU'   T	(       a  MR  Mp     T
$ )zAMore efficient internal routine for strongly_connected_componentsc                 x   > [        T5      nU=TU '   TU '   S TU '   TR                  U [        TU    5      45        g r0   )r&   rA   rG   )r   indexr   	callstackr%   lowlinkstacks     r    r   -_strongly_connected_components.<locals>.start  sB    E
"''
WQZa!T$q']+,r,   c                 H  > TU    TU    :X  a_  TR                  5       S   /nUS   U La,  UR                  TR                  5       S   5        US   U La  M,  TR                  US S S2   5        TR                  5       u  p#T(       a  TS   u  p[        TU    TU   5      TU '   g g )Nr   r{   )popitemrA   r   r   )	r   	componentr   r)   r   
componentsr%   r   r   s	       r    finish._strongly_connected_components.<locals>.finish  s    2;'"+%+,IB-r)  !34 B-r)i"o.bMEBgbk72;7GBK r,   r{   )r   rg   ra   r   )r   r   nomorer   r  r   r   rj   r   r   r  r%   r   r   s    `       @@@@@r    r   r     s    ( GGMEIJXF- -
8 
8 <aimGBc"B|r
7"b	u!'"+wr{; i	 " r,   c                 f    U u  p/ nU H  u  pEUR                  XE4XT4/5        M     [        X45      $ )aY  
Connected components of an undirected graph or weakly connected components
of a directed graph.


Parameters
==========

G : tuple[list, list[tuple[T, T]]
    A tuple consisting of a list of vertices and a list of edges of
    a graph whose connected components are to be found.


Examples
========


Given an undirected graph::

    graph {
        A -- B
        C -- D
    }

.. graphviz::

    graph {
        A -- B
        C -- D
    }

We can find the connected components using this function if we include
each edge in both directions::

    >>> from sympy.utilities.iterables import connected_components

    >>> V = ['A', 'B', 'C', 'D']
    >>> E = [('A', 'B'), ('B', 'A'), ('C', 'D'), ('D', 'C')]
    >>> connected_components((V, E))
    [['A', 'B'], ['C', 'D']]

The weakly connected components of a directed graph can found the same
way.


Notes
=====

The vertices of the graph must be hashable for the data structures used.
If the vertices are unhashable replace them with integer indices.

This function uses Tarjan's algorithm to compute the connected components
in `O(|V|+|E|)` (linear) time.


References
==========

.. [1] https://en.wikipedia.org/wiki/Component_%28graph_theory%29
.. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm


See Also
========

sympy.utilities.iterables.strongly_connected_components

)r?   r   )r   r   r   E_undirectedr   r   s         r    connected_componentsr    sB    N DALbXx01 (!):;;r,   c                 T    [        U 5      S:X  a  / $ U[        U 5      -  nXS U SU -   $ )z
Left rotates a list x by the number of steps specified
in y.

Examples
========

>>> from sympy.utilities.iterables import rotate_left
>>> a = [0, 1, 2]
>>> rotate_left(a, 1)
[1, 2, 0]
r   Nr   r4   ys     r    rotate_leftr  g  s5     1v{		CF
AR51Ra5=r,   c                 l    [        U 5      S:X  a  / $ [        U 5      U[        U 5      -  -
  nXS U SU -   $ )z
Right rotates a list x by the number of steps specified
in y.

Examples
========

>>> from sympy.utilities.iterables import rotate_right
>>> a = [0, 1, 2]
>>> rotate_right(a, 1)
[2, 0, 1]
r   Nr   r
  s     r    rotate_rightr  z  s>     1v{	ASVAR51Ra5=r,   c                    SSK Jn  Uc  UnX -   nS/[        U5      -  nSn[        S[        U5      5       H  nX6   nXFU-
  S-
     nUS:w  aG  XsXX-   S-      :w  a:  U" U5      U" X5U-   S-      5      :  a  Xh-
  S-
  nXH   nUS:w  a  XsXX-   S-      :w  a  M:  XsXX-   S-      :w  a  U" U5      U" X5   5      :  a  UnSXFU-
  '   M  US-   XFU-
  '   M     U$ )a  
Returns the number of steps of left rotation required to
obtain lexicographically minimal string/list/tuple, etc.

Examples
========

>>> from sympy.utilities.iterables import least_rotation, rotate_left
>>> a = [3, 1, 5, 1, 2]
>>> least_rotation(a)
3
>>> rotate_left(a, _)
[1, 2, 3, 1, 5]

References
==========

.. [1] https://en.wikipedia.org/wiki/Lexicographically_minimal_string_rotation

r   Idr{   r   )(sympy.functions.elementary.miscellaneousr  r&   r(   )	r4   r   r  r   fr   r   sjr   s	            r    least_rotationr    s    * <
{"C	A	s1vA	A1SV_Tc!eH2g"!#a%.2wQs1uX&CEA 2g"!#a%. 13q5>2wQT"AcFqSAcF  Hr,   c           	   #     #    SSK Jn  Uc  [        U [        5      (       ak  [	        S U R                  5        5       5      (       a  [        S5      e[        U R                  5       5      nX:  a  gU" U 5       Vs/ s H  oUX   /PM
     nnOC[        U 5      n [        U 5      nX:  a  g [        U 5      n U" U 5       Vs/ s H  oUX   4PM
     nnA O[        S U 5       5      nX:  d  U(       d  / v   g[        U5       Hp  u  nu  pWXq:  a  U/U-  v   US	-
  n[        [        X5      SS
5       H<  n[!        SX-
  X&S	-   S 5       H!  nU/U-  U-   n	[        U	5      U:X  d  M  U	v   M#     M>     Mr     gs  snf s  snf ! [         a=    [        U" U 5      5      n [        U SS9 Vs/ s H  n[        U5      PM     Os  snf nn Nf = f7f)a  
Return the unique combinations of size ``n`` from multiset ``m``.

Examples
========

>>> from sympy.utilities.iterables import multiset_combinations
>>> from itertools import combinations
>>> [''.join(i) for i in  multiset_combinations('baby', 3)]
['abb', 'aby', 'bby']

>>> def count(f, s): return len(list(f(s, 3)))

The number of combinations depends on the number of letters; the
number of unique combinations depends on how the letters are
repeated.

>>> s1 = 'abracadabra'
>>> s2 = 'banana tree'
>>> count(combinations, s1), count(multiset_combinations, s1)
(165, 23)
>>> count(combinations, s2), count(multiset_combinations, s2)
(165, 54)

r   orderedNc              3   >   #    U  H  n[        U5      S :  v   M     g7fr   r   r   r   s     r    r!   (multiset_combinations.<locals>.<genexpr>       5*Q6!9q=*   counts cannot be negativeFr\   c              3   *   #    U  H	  u  pUv   M     g 7fr0   r   r   r   r   s      r    r!   r    s      adaar   r   r{   )sympy.core.sortingr  r8   rw   anyvaluesr=   rN   rJ   r&   ry   r   r^   r   r(   r   multiset_combinations)
r*   rH   r]   r  Nr   r   r   r   rW   s
             r    r%  r%    s    4 +ya5!((*555 !<==AHHJAu$+AJ/JqQTJA/AQAAAu@QK(/
3
1Y
3   a  uA"1IAvvc!eE3q9a,.tQUA!efIFAQB2w!|  G -	 &' 0 4 @$&+A&>?&>T!W&>??@s[   A8G:E4	G)E> >E9E> BG#G9E> >'G%F;:GGGGc              #   B  #    SSK Jn  Uc  [        U [        5      (       aL  [	        S U R                  5        5       5      (       a  [        S5      eU" U 5       Vs/ s H  oDX   /PM
     nnO4[        U" U 5      5      n [        U SS9 Vs/ s H  n[        U5      PM     nnA U Vs/ s H  ofS   S:  d  M  UPM     nn[        S	 U 5       5      nU(       a  Ub   X:  d  US:  a  U(       d  Ub  US:X  a  / v   gUS:X  a  U H
  u  pIU/v   M     g[        U5      S:X  a3  US   u  pIUc  U	OX::  a  UOSn	[        U	5       Vs/ s H  oTPM     snv   g[        S
 U 5       5      (       a6  [        U VV	s/ s H  u  pIUPM	     sn	nU5       H  n
[        U
5      v   M     gUb  UOUn[        U5       HN  u  nu  pIXu   S==   S-  ss'   [        SUS-
  U5       H  nU(       d  M  U/U-   v   M     Xu   S==   S-  ss'   MP     gs  snf s  snf s  snf s  snf s  sn	nf 7f)aG  
Return the unique permutations of multiset ``m``.

Examples
========

>>> from sympy.utilities.iterables import multiset_permutations
>>> from sympy import factorial
>>> [''.join(i) for i in multiset_permutations('aab')]
['aab', 'aba', 'baa']
>>> factorial(len('banana'))
720
>>> len(list(multiset_permutations('banana')))
60
r   r  Nc              3   >   #    U  H  n[        U5      S :  v   M     g7fr   r   r  s     r    r!   (multiset_permutations.<locals>.<genexpr>	  r  r  r  Fr  r   c              3   *   #    U  H	  oS    v   M     g7fr   r   )r   gis     r    r!   r)    s     !bebr   c              3   0   #    U  H  u  pUS :H  v   M     g7fr   r   r!  s      r    r!   r)    s     #Q!Vs   )r"  r  r8   rw   r#  r$  r=   rJ   r^   rN   r&   r(   r'   r   r   multiset_permutations)r*   sizer]   r  r   r   r+  doSUMr   pr   s               r    r-  r-    s      +ya5!((*555 !<==$+AJ/JqQTJA/AWQZ A"'E":;":Qa":A;	&qqEAI"qB	&
!b!
!C!tzTAXdldaiH	DA#I 	RA!uADID1(#(Qq(##	##	#	#R0RTQqR0$7Aq'M 8 'tS"2IAvE!HMH*42>1#'M ? E!HMH '/ 0 <	& $0sP   AHH* H
H
H&H6H<BHH'H4H
AH%:Hc                     Uc  [        U5      S-   nO[        U[        5      (       a  X!p![        U5       Vs/ s H  n/ PM     nn[	        U5       H  u  p5XE   R                  X   5        M     U$ s  snf )a=  
Return the partition of seq as specified by the partition vector.

Examples
========

>>> from sympy.utilities.iterables import _partition
>>> _partition('abcde', [1, 0, 1, 2, 0])
[['b', 'e'], ['a', 'c'], ['d']]

Specifying the number of bins in the partition is optional:

>>> _partition('abcde', [1, 0, 1, 2, 0], 3)
[['b', 'e'], ['a', 'c'], ['d']]

The output of _set_partitions can be passed as follows:

>>> output = (3, [1, 0, 1, 2, 0])
>>> _partition('abcde', *output)
[['b', 'e'], ['a', 'c'], ['d']]

See Also
========

combinatorics.partitions.Partition.from_rgs

r   )maxr8   rQ   r(   r   rA   )rS   vectorr*   r   r1  r   s         r    
_partitionr5  *  sk    8 	yK!O	FC	 	 1XXXA&!	CF "H 	s   A0c              #   &  #    S/U -  nS/U -  nSnX24v   X0:w  au  U n US-  nX$   nX   S:w  a  OSX$'   M  US-  nXRU'   US-  nX4U -
  -  nUS==   X-
  -  ss'   XS:X  a	  SX'   US-  nXS-
  ==   S-  ss'   X==   S-  ss'   X24v   X0:w  a  Mt  gg7f)a[  Cycle through all partitions of n elements, yielding the
current number of partitions, ``m``, and a mutable list, ``q``
such that ``element[i]`` is in part ``q[i]`` of the partition.

NOTE: ``q`` is modified in place and generally should not be changed
between function calls.

Examples
========

>>> from sympy.utilities.iterables import _set_partitions, _partition
>>> for m, q in _set_partitions(3):
...     print('%s %s %s' % (m, q, _partition('abc', q, m)))
1 [0, 0, 0] [['a', 'b', 'c']]
2 [0, 0, 1] [['a', 'b'], ['c']]
2 [0, 1, 0] [['a', 'c'], ['b']]
2 [0, 1, 1] [['a'], ['b', 'c']]
3 [0, 1, 2] [['a'], ['b'], ['c']]

Notes
=====

This algorithm is similar to, and solves the same problem as,
Algorithm 7.2.1.5H, from volume 4A of Knuth's The Art of Computer
Programming.  Knuth uses the term "restricted growth string" where
this code refers to a "partition vector". In each case, the meaning is
the same: the value in the ith element of the vector specifies to
which part the ith set element is to be assigned.

At the lowest level, this code implements an n-digit big-endian
counter (stored in the array q) which is incremented (with carries) to
get the next partition in the sequence.  A special twist is that a
digit is constrained to be at most one greater than the maximum of all
the digits to the left of it.  The array p maintains this maximum, so
that the code can efficiently decide when a digit can be incremented
in place or whether it needs to be reset to 0 and trigger a carry to
the next digit.  The enumeration starts with all the digits 0 (which
corresponds to all the set elements being assigned to the same 0th
part), and ends with 0123...n, which corresponds to each set element
being assigned to a different, singleton, part.

This routine was rewritten to use 0-based lists while trying to
preserve the beauty and efficiency of the original algorithm.

References
==========

.. [1] Nijenhuis, Albert and Wilf, Herbert. (1978) Combinatorial Algorithms,
    2nd Ed, p 91, algorithm "nexequ". Available online from
    https://www.math.upenn.edu/~wilf/website/CombAlgDownld.html (viewed
    November 17, 2012).

r   r   Nr   )rH   r1  qncr*   r   s         r    _set_partitionsr9  P  s     l 
AA	
AA	
B
%K
'FAAtqyAD  	
Q!	Q
!e	!7AE!GB	a%A		e% 's   BBBc           
   #     #    [        U [        5      (       a  U nU(       a  X:  a  g[        [        U5      5      n US:X  a	  U SS /v   g[	        U5       HX  u  p4Ub  X1:X  d  M  [        U5       Vs/ s H  n/ PM     nn[        U5       H  nXdU      R                  X   5        M     Uv   MZ     g[        U 5      S:X  a  [        U [        5      (       a  U /n [        U 5      (       d{  [        U 5      nU(       a  X:  a  gUS:X  a	  U SS /v   gU SS n[        X!SS9 H@  u  pUb  X:X  d  M  / n[        U	5       H  n
UR                  Xz-  /X   -  5        M     Uv   MB     gSSKJn  [        U" U 5      5      n [        U 5      nU(       a  X:  a  gUS:X  a	  U SS /v   g[        [        U S5      6 u  p[        U5      [        U 5      :  a[  U(       a4  [!        5       nUR#                  XS-
  U5       H  n[%        X5      v   M     g['        U5       H  n[%        X5      v   M     g[	        U5       H|  u  p4Ub  X1:X  d  M  [        U5       Vs/ s H  n/ PM     nn[        U5       H  nXdU      R                  U5        M     U VVs/ s H  oU Vs/ s H  nU U   PM
     snPM     snnv   M~     gs  snf s  snf s  snf s  snnf 7f)a  
Return unique partitions of the given multiset (in list form).
If ``m`` is None, all multisets will be returned, otherwise only
partitions with ``m`` parts will be returned.

If ``multiset`` is an integer, a range [0, 1, ..., multiset - 1]
will be supplied.

Examples
========

>>> from sympy.utilities.iterables import multiset_partitions
>>> list(multiset_partitions([1, 2, 3, 4], 2))
[[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]],
[[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]],
[[1], [2, 3, 4]]]
>>> list(multiset_partitions([1, 2, 3, 4], 1))
[[[1, 2, 3, 4]]]

Only unique partitions are returned and these will be returned in a
canonical order regardless of the order of the input:

>>> a = [1, 2, 2, 1]
>>> ans = list(multiset_partitions(a, 2))
>>> a.sort()
>>> list(multiset_partitions(a, 2)) == ans
True
>>> a = range(3, 1, -1)
>>> (list(multiset_partitions(a)) ==
...  list(multiset_partitions(sorted(a))))
True

If m is omitted then all partitions will be returned:

>>> list(multiset_partitions([1, 1, 2]))
[[[1, 1, 2]], [[1, 1], [2]], [[1, 2], [1]], [[1], [1], [2]]]
>>> list(multiset_partitions([1]*3))
[[[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]]

Counting
========

The number of partitions of a set is given by the bell number:

>>> from sympy import bell
>>> len(list(multiset_partitions(5))) == bell(5) == 52
True

The number of partitions of length k from a set of size n is given by the
Stirling Number of the 2nd kind:

>>> from sympy.functions.combinatorial.numbers import stirling
>>> stirling(5, 2) == len(list(multiset_partitions(5, 2))) == 15
True

These comments on counting apply to *sets*, not multisets.

Notes
=====

When all the elements are the same in the multiset, the order
of the returned partitions is determined by the ``partitions``
routine. If one is counting partitions then it is better to use
the ``nT`` function.

See Also
========

partitions
sympy.combinatorics.partitions.Partition
sympy.combinatorics.partitions.IntegerPartition
sympy.functions.combinatorial.numbers.nT

Nr   Tr.  r   r  F)r8   rQ   rJ   r(   r9  rA   r&   r   has_variety
partitionsr   r?   r"  r  rK   r^   r   
enum_ranger   r   )ry   r*   rH   r8  r7  r   rW   r4   r.  r1  r   r  elementsmultiplicitiesmptstater   s                    r    multiset_partitionsrC    s    Z (C  a>6A;- %Q'EByBG"'),)Qb),qAtHOOHK0 " ( 	
8}j377:x   M6A;-RaL!!T2GDyDIAIIqseADj) # 3 	/)*M6A;-
 $'h(>#? x=3x=( 02 ^^NaCCE&u77 D 7~FE&u77 G )+9&+Bi0i"iB0"1XQ4* &=?@R3AHQK3R@@ ,o -r 1 4@sV   AK
$K
1J5=B-K
.DK
K
J:/K
	KJ?#K*K
?KK
c              #   *  #    U S::  d(  Ub  US:  d  Ub  US:  d  U(       a"  U(       a  X-  U :  a  U(       a  S0 4v   g0 v   gUc  U nO[        X5      n[        U=(       d    U U 5      n[        U 5      [        U5      [        U5      p!n [        X5      u  pEX$0nU/nU(       a  SXe'   UR                  U5        X-
  [	        U5      -
  nU(       a,  [        UR                  5       5      UR                  5       4v   OUR                  5       v   US/:w  a  US   S:X  a  US	 UR                  S5      n	X-  nOSn	 US   n
Xj   S-
  =oU
'   X-  n	US:X  a  US	 Xj	 US-  nU
S-  n
[        X5      u  pEU[	        U5      -   nX:  a
  U(       d  gMT  XFU
'   UR                  U
5        U(       a  SXe'   UR                  U5         X-  nU(       a,  [        UR                  5       5      UR                  5       4v   OUR                  5       v   US/:w  a  M  gg7f)a  Generate all partitions of positive integer, n.

Each partition is represented as a dictionary, mapping an integer
to the number of copies of that integer in the partition.  For example,
the first partition of 4 returned is {4: 1}, "4: one of them".

Parameters
==========
n : int
m : int, optional
    limits number of parts in partition (mnemonic: m, maximum parts)
k : int, optional
    limits the numbers that are kept in the partition (mnemonic: k, keys)
size : bool, default: False
    If ``True``, (M, P) is returned where M is the sum of the
    multiplicities and P is the generated partition.
    If ``False``, only the generated partition is returned.

Examples
========

>>> from sympy.utilities.iterables import partitions

The numbers appearing in the partition (the key of the returned dict)
are limited with k:

>>> for p in partitions(6, k=2):  # doctest: +SKIP
...     print(p)
{2: 3}
{1: 2, 2: 2}
{1: 4, 2: 1}
{1: 6}

The maximum number of parts in the partition (the sum of the values in
the returned dict) are limited with m (default value, None, gives
partitions from 1 through n):

>>> for p in partitions(6, m=2):  # doctest: +SKIP
...     print(p)
...
{6: 1}
{1: 1, 5: 1}
{2: 1, 4: 1}
{3: 2}

References
==========

.. [1] modified from Tim Peter's version to allow for k and m values:
       https://code.activestate.com/recipes/218332-generator-for-integer-partitions/

See Also
========

sympy.combinatorics.partitions.Partition
sympy.combinatorics.partitions.IntegerPartition

r   Nr   r{   )	r   r   rO   rA   boolrN   r$  copyr   )rH   r*   r   r.  r7  rmskeysroomreuser   newcountneeds                r    r=  r=  =  s    v 	
Q	!a%	!a%	aAC!G R%K 	 HyIAFAAQiF1I!A!<DA
B3DA547?D"))+	))ggi
1#+8q=RFF1IEMDE RA!uqy(H!uJE1}HbeAID FA%#DAtAw;D{qEKKNAbiik"BGGI--'')OM 1#+s   HHHc              #   8  #    U S:  d	  Ub  US:  a  / v   gUc  S/U -  nSnU nUS:  aw  US-  nX5   S-   nUSU-  :  a  XcU'   XF-  nUS-  nUSU-  :  a  M  US-   nXd::  a#  XcU'   XCU'   USUS-    v   US-  nUS-  nXd::  a  M#  Xd-   X5'   X5   S-
  nUSU v   US:  a  Mv  ggUS:X  a  U /v   gX:X  a	  S/U -  v   g[        SX-  S-   5       H  nU/U-  nXU-  -
  nU(       d  U(       a  Uv   M$  M&  U(       dH  Xa::  aC  [        USS9 H3  n	[        U	5      n
U	 Vs/ s H  oU-   PM	     snX:* S& Uv   U/U
-  X:* S& M5     Mu  [        SU5       H9  n
[        XjSS9 H(  n	U	 Vs/ s H  oU-   PM	     snX:* S& Uv   U/U
-  X:* S& M*     M;     M     gs  snf s  snf 7f)	a  Generates ordered partitions of integer *n*.

Parameters
==========
n : int
m : int, optional
    The default value gives partitions of all sizes else only
    those with size m. In addition, if *m* is not None then
    partitions are generated *in place* (see examples).
sort : bool, default: True
    Controls whether partitions are
    returned in sorted order when *m* is not None; when False,
    the partitions are returned as fast as possible with elements
    sorted, but when m|n the partitions will not be in
    ascending lexicographical order.

Examples
========

>>> from sympy.utilities.iterables import ordered_partitions

All partitions of 5 in ascending lexicographical:

>>> for p in ordered_partitions(5):
...     print(p)
[1, 1, 1, 1, 1]
[1, 1, 1, 2]
[1, 1, 3]
[1, 2, 2]
[1, 4]
[2, 3]
[5]

Only partitions of 5 with two parts:

>>> for p in ordered_partitions(5, 2):
...     print(p)
[1, 4]
[2, 3]

When ``m`` is given, a given list objects will be used more than
once for speed reasons so you will not see the correct partitions
unless you make a copy of each as it is generated:

>>> [p for p in ordered_partitions(7, 3)]
[[1, 1, 1], [1, 1, 1], [1, 1, 1], [2, 2, 2]]
>>> [list(p) for p in ordered_partitions(7, 3)]
[[1, 1, 5], [1, 2, 4], [1, 3, 3], [2, 2, 3]]

When ``n`` is a multiple of ``m``, the elements are still sorted
but the partitions themselves will be *unordered* if sort is False;
the default is to return them in ascending lexicographical order.

>>> for p in ordered_partitions(6, 2):
...     print(p)
[1, 5]
[2, 4]
[3, 3]

But if speed is more important than ordering, sort can be set to
False:

>>> for p in ordered_partitions(6, 2, sort=False):
...     print(p)
[1, 5]
[3, 3]
[2, 4]

References
==========

.. [1] Generating Integer Partitions, [online],
    Available: https://jeromekelleher.net/generating-integer-partitions.html
.. [2] Jerome Kelleher and Barry O'Sullivan, "Generating All
    Partitions: A Comparison Of Two Encodings", [online],
    Available: https://arxiv.org/pdf/0909.2331v2.pdf
r   Nr{   r   r   F)sortT)r(   ordered_partitionsr&   )rH   r*   rO  ar  r   r4   wbaxmir   s               r    rP  rP    s    \ 	1u!a% y
 CE!eFAqAq1u*!Q q1u* AA&!!QiQQ & 5ADqABQ%K! !e" 
ac		
c!e q!$(#AAAaCAG af,QU;BRB.01b1ub1AcdGG c"fAcdG	 <  1+B0TB24"5"Qq5""5#$#$#b&#$ C & $ 2 #6s1   AF+FF A;FF)9F"F
0*Fc              #   .  #    SSK JnJn  [        SU" U" U 5      5      -  5      nSn/ nU(       a+  XC-   U ::  a  UR	                  U5        XC-  nUS-  nU(       a  M+  [        U5      S-
  U S-  -
  nUS:  a  Uv   XV   S:X  a  SXV'   UR	                  S5        US-  nM.  UR	                  S5        XV==   S-  ss'   XV   =ouUS-   '   US-  nUS:  a4  U[        U5      U-
  S-
  ::  a  XW* S-   S2	 US-  nXuU'   OUS-  nUS:  a  M4  US:  a  M  S/U -  v   g7f)a  
Generates the binary partition of *n*.

A binary partition consists only of numbers that are
powers of two. Each step reduces a `2^{k+1}` to `2^k` and
`2^k`. Thus 16 is converted to 8 and 8.

Examples
========

>>> from sympy.utilities.iterables import binary_partitions
>>> for i in binary_partitions(5):
...     print(i)
...
[4, 1]
[2, 2, 1]
[2, 1, 1, 1]
[1, 1, 1, 1, 1]

References
==========

.. [1] TAOCP 4, section 7.2.1.5, problem 64

r   )ceillog2r   r   N)mathrW  rX  rQ   rA   r&   )rH   rW  rX  poweracc	partitionlast_numr4   s           r    binary_partitionsr^  I  sL    4  DaM"#E
CI
;!U#LC!	 % 9~!QU+H
a-!#"#IQMH!&/&99hl#A!eC	NX-11b1fg&A&'(#a !e a-$ #a%Ks   ADB'DD	Dc           	        ^ SSK Jn  SSKJn  [	        U [
        [        X45      (       a  g[        5       m [        U4S jU  5       5      $ ! [         a,    [        U 5      [        [        [        U 5      5      5      :g  s $ f = f)zReturn True if there are any duplicate elements in ``seq``.

Examples
========

>>> from sympy import has_dups, Dict, Set
>>> has_dups((1, 2, 1))
True
>>> has_dups(range(3))
False
>>> all(has_dups(c) is False for c in (set(), Set(), dict(), Dict()))
True
r   )Dict)SetFc              3   b   >#    U  H$  oT;   d  TR                  U5      (       d  M   S v   M&     g7fTN)add)r   r   uniques     r    r!   has_dups.<locals>.<genexpr>  s!     EAVvzz!}44s   /	/)sympy.core.containersr`  sympy.sets.setsra  r8   rw   r2   r#  r   r&   rJ   uniq)rS   r`  ra  re  s      @r    has_dupsrj    sj     +##c4-..UF0EEEE 03x3tDI///0s   A 3B Bc                 P    [        U 5       H  u  pUS:X  a  UnM  UW:w  d  M    g   g)zReturn True if there are any different elements in ``seq``.

Examples
========

>>> from sympy import has_variety

>>> has_variety((1, 2, 1))
True
>>> has_variety((1, 1, 1))
False
r   TF)r   )rS   r   r   re   s       r    r<  r<    s/     #6HH}  r,   c              #     ^ ^#     [        T 5      mUU 4S jn [        5       nU=(       d    / n[        T 5       H/  u  pEXS;   a  M  UR	                  U5      (       a  M$  Uv   U" 5         M1     g! [         a    Sm Njf = f! [         ah    WU;  a  Uv   U" 5         UR                  U5        [        T S5      (       a  [        T WS-   S U5       Sh  vN     g[        T U5       Sh  vN     gf = f7f)a  
Yield unique elements from ``seq`` as an iterator. The second
parameter ``result``  is used internally; it is not necessary
to pass anything for this.

Note: changing the sequence during iteration will raise a
RuntimeError if the size of the sequence is known; if you pass
an iterator and advance the iterator you will change the
output of this routine but there will be no warning.

Examples
========

>>> from sympy.utilities.iterables import uniq
>>> dat = [1, 4, 1, 5, 4, 2, 1, 2]
>>> type(uniq(dat)) in (list, tuple)
False

>>> list(uniq(dat))
[1, 4, 5, 2]
>>> list(uniq(x for x in dat))
[1, 4, 5, 2]
>>> list(uniq([[1], [2, 1], [1]]))
[[1], [2, 1]]
Nc                  B   > T b  [        T5      T :w  a  [        S5      eg g )Nz&sequence changed size during iteration)r&   RuntimeError)rH   rS   s   r    checkuniq.<locals>.check  s'     =SX]GHH +=r,   __getitem__r   )r&   r   r2   r   rd  rA   r>   ri  )rS   rC   ro  seenr   r   rH   s   `     @r    ri  ri    s     4HI)u2cNDAI! #    )F?GGMM!3&&CAK000C((()s{   C4A- C4(A? A? A? ,C4-A<9C4;A<<C4?AC1CC1C4C1(C+)C1.C40C11C4c              #     #    [        U 5      n U S:  a  [        S5      eU S:X  a  Sv   g	U S:X  a	  Sv   Sv   g	U S:X  a  / SQ S	h  vN   g	U S-
  nS
/S/U-  -   n[        [        U 5      5      n [	        U5      v   Sn[        U 5       H!  nX%   (       d  M  X5   US   :  d  M  XSU   4nM#     Uu  pVUc  g	XRU   -   nX7   X5   sX5'   X7'   X'   X%   sX%'   X''   US
:X  d  Xq:X  d  X7X'   -      X7   :  a  S
X''   [        U5       H  nX5   X7   :  d  M  SX%'   M     [        US-   U 5       H  nX5   X7   :  d  M  SX%'   M     M   N7f)a{	  Return permutations of [0, 1, ..., n - 1] such that each permutation
differs from the last by the exchange of a single pair of neighbors.
The ``n!`` permutations are returned as an iterator. In order to obtain
the next permutation from a random starting permutation, use the
``next_trotterjohnson`` method of the Permutation class (which generates
the same sequence in a different manner).

Examples
========

>>> from itertools import permutations
>>> from sympy.utilities.iterables import generate_bell
>>> from sympy import zeros, Matrix

This is the sort of permutation used in the ringing of physical bells,
and does not produce permutations in lexicographical order. Rather, the
permutations differ from each other by exactly one inversion, and the
position at which the swapping occurs varies periodically in a simple
fashion. Consider the first few permutations of 4 elements generated
by ``permutations`` and ``generate_bell``:

>>> list(permutations(range(4)))[:5]
[(0, 1, 2, 3), (0, 1, 3, 2), (0, 2, 1, 3), (0, 2, 3, 1), (0, 3, 1, 2)]
>>> list(generate_bell(4))[:5]
[(0, 1, 2, 3), (0, 1, 3, 2), (0, 3, 1, 2), (3, 0, 1, 2), (3, 0, 2, 1)]

Notice how the 2nd and 3rd lexicographical permutations have 3 elements
out of place whereas each "bell" permutation always has only two
elements out of place relative to the previous permutation (and so the
signature (+/-1) of a permutation is opposite of the signature of the
previous permutation).

How the position of inversion varies across the elements can be seen
by tracing out where the largest number appears in the permutations:

>>> m = zeros(4, 24)
>>> for i, p in enumerate(generate_bell(4)):
...     m[:, i] = Matrix([j - 3 for j in list(p)])  # make largest zero
>>> m.print_nonzero('X')
[XXX  XXXXXX  XXXXXX  XXX]
[XX XX XXXX XX XXXX XX XX]
[X XXXX XX XXXX XX XXXX X]
[ XXXXXX  XXXXXX  XXXXXX ]

See Also
========

sympy.combinatorics.permutations.Permutation.next_trotterjohnson

References
==========

.. [1] https://en.wikipedia.org/wiki/Method_ringing

.. [2] https://stackoverflow.com/questions/4856615/recursive-permutation/4857018

.. [3] https://web.archive.org/web/20160313023044/http://programminggeeks.com/bell-algorithm-for-permutation/

.. [4] https://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm

.. [5] Generating involutions, derangements, and relatives by ECO
       Vincent Vajnovszki, DMTCS vol 1 issue 12, 2010

r   zn must be a positive integer)r   r   )r   r   )r   r      ))r   r   r   )r   r   r   )r   r   r   )r   r   r   )r   r   r   )r   r   r   Nr   r{   Nr{   )r   r=   rJ   r(   r   )rH   r*   oplbigr   r)   r   s           r    generate_bellry    so    B 	q	A1u788Av
	
a	
aUUUESB46\qN(NC1X55QTCF]qT'C  DAyqE	AqtJAD!$5"%LBE25 Av1Y<!$#61X4!$;BE  1q5!_4!$;BE %/  	Vs,   AEE AE	E%A'E"E6Ec              #      #    [        [        U 5      5      n[        U5       H  nU H  nX"U      U:w  d  M    M     Uv   M      g7f)ap  
Generates involutions.

An involution is a permutation that when multiplied
by itself equals the identity permutation. In this
implementation the involutions are generated using
Fixed Points.

Alternatively, an involution can be considered as
a permutation that does not contain any cycles with
a length that is greater than two.

Examples
========

>>> from sympy.utilities.iterables import generate_involutions
>>> list(generate_involutions(3))
[(0, 1, 2), (0, 2, 1), (1, 0, 2), (2, 1, 0)]
>>> len(list(generate_involutions(4)))
10

References
==========

.. [1] https://mathworld.wolfram.com/PermutationInvolution.html

N)rJ   r(   r   )rH   idxr1  r   s       r    generate_involutionsr|  S  sD     8 uQx.C#A1w!|  G s
   1AAc           
   #     ^ ^^^^^^#    SSK Jn   [        T 5      n[        UR                  5       5      n	[        T 5      mU	S-  T:  a  g[        U5      T:X  a  [        T 5       Sh  vN   gU H  n
X*   U	:X  d  M    O   [        T5       Vs/ s H  nT U   W
:w  d  M  UPM     nn[        T5       Vs/ s H  nT U   W
:X  d  M  UPM     nnS/T-  mSU	-  T:X  a[  U H  nW
TU'   M
     [        U Vs/ s H  nT U   PM
     sn5       H   n[        X5       H
  u  p~UTU'   M     Tv   M"     S/T-  TSS& gTSU	-  -
  S:X  a  [        UR                  5       5      TU	-
  S-   :X  a  [        U5       H  u  pUSU XS-   S -   nU H  nW
TU'   M
     [!        U Vs/ s H  nT U   PM
     sn5       HF  nT U   TU'   [        X5       H
  u  pUTU'   M     UnU H  nTU   TU   sTU'   TU'   Tv   UnM     MH     M     S/T-  TSS& gUU U4S jmUUU 4S jmUUUUU4S jm[#        UR%                  5       S	 S
9mT" [        T5      S-
  5       Sh  vN   S/T-  TSS& g! [         a    [	        [        U" [        T 5      5      5      5      n/ nT  H(  nU H  nX6   U:X  d  M  UR                  U5          M&     M*     [        U5       H   nU Vs/ s H  oU   PM	     Os  snf snv   M"      gf = f GNs  snf s  snf s  snf s  snf  N7f)aV  Generate derangements of the elements of s *in place*.

Examples
========

>>> from sympy.utilities.iterables import multiset_derangements, uniq

Because the derangements of multisets (not sets) are generated
in place, copies of the return value must be made if a collection
of derangements is desired or else all values will be the same:

>>> list(uniq([i for i in multiset_derangements('1233')]))
[[None, None, None, None]]
>>> [i.copy() for i in multiset_derangements('1233')]
[['3', '3', '1', '2'], ['3', '3', '2', '1']]
>>> [''.join(i) for i in multiset_derangements('1233')]
['3312', '3321']
r   r  Nr   r   c               3     >#    TS   S   n TS   S   nTS   S   nTS   S   n/ n/ n/ n[        [        T5      5       HT  nT
U   b  M  TU   U :X  a  UR                  U5        M'  TU   U:X  a  UR                  U5        MC  UR                  U5        MV     [        U5      U:  d  [        U5      U:  a  gU H  nU T
U'   M
     U H  nUT
U'   M
     [        Xa[        U5      -
  5       H9  nU H  n	U T
U	'   M
     U H  nT
U   b  M  UT
U'   M     T
v   U H  nST
U'   M
     M;     U H  nST
U'   M
     U H  nST
U'   M
     g7f)z]Place the last two elements into the partially completed
derangement, and yield the results.
r   r   N)r(   r&   rA   r   )rQ  a_ctrS  b_ctforced_aforced_b	open_freer   a_placea_posrW   r   r   s             r    finish_derangements2multiset_derangements.<locals>.finish_derangements  sp    
 GAJAwqzGAJAwqz 	s1vA!u}Q419OOA&qTQYOOA&$$Q'  x=43x=4#7ABqE ABqE #Ic(m/CDG 5	 !a5=BqE  H1  E ABqE ABqE s   AE	B9E<Ec                 l   > [        T5       Vs/ s H  nTU   b  M  TU   U :w  d  M  UPM     sn$ s  snf r0   )r(   )r   r   rH   rW   r   s     r    iopen$multiset_derangements.<locals>.iopen	  s3     !8C8ar!u18CCCs   
111c              3      >#    U S:X  a  T" 5        S h  vN   g T	U    u  p[        T" U5      U5       H2  nU H  nUTU'   M
     T" U S-
  5       S h  vN   U H  nS TU'   M
     M4     g  NU N7fNr   r   )
r   Mmxr   iir/  r  r  rW   r   s
        r    r/  !multiset_derangements.<locals>.do	  s     6 +,,, GEA!%(B/BBrF  a!e9$$ B!BrF  0 - %s!   A.A*=A.A,A.,A.c                     U S   U S   4$ )Nr   r   r   r3   s    r    <lambda>'multiset_derangements.<locals>.<lambda>0	  s    AaD!A$<r,   r   )r"  r  ry   r   rw   r   ri  rA   multiset_derangementsr3  r$  r&   _set_derangementsr(   r-  rK   r   r   rx   )r   r  rH  r   hsir   r   r   r  r  inonMiMr1  pii1ifillr/  r  r  rH   rW   r   s   `                @@@@@@r    r  r  x  s*    & +a[ 
RYY[	BAA 
!tax 2w!|$Q''' 5B;  a.1AaDAIQE.1X	+X1!XB	+
B 	tqyABqE  'e'<e!e'<=AR1 $H >
 q1 	1R4x1}RYY[)QVaZ7u%EA"1Icd+E1 !"7A1Q4"7822 ZEABqE (A#%a5"Q%LBqE2a5HA  9	 & q1/bD" "* "((*"78D#d)a-   F1HBqEE  9WT!W-./B6R<HHQK  
 'q)A#$%1aq61%% *2 	( /	+ (=" #8D !s   LI  AL'K2(L<LK5K5$L3K:K:
(L2K?BLL
(B)LL	L ?K/#,K/KK/,L.K//L5Lc                   ^^ Tc  SSK nUR                  mU4S jmU4S jn[        U 5      n[        U 5      n[	        UR                  5       S S9nUS   u  px[        U 5      n	SU-  U-
  n
U
S:  a  U(       a  [        S	5      e[        U 5       VVs/ s H  u  pXS   S   :X  d  M  UPM     nnnU" X5        [	        USU
 5      n[        U 5      n[        U5       H  nUR                  U5        M     [        UT5      nU H  nUR                  XS   S   5        M     [        U 5      [        L a  S
R                  U5      $ U$ U	[        U5      :X  a9  [        U 5      n T" U5        [!        S [#        X5       5       5      (       a   U$ M-  S/U	-  n SnU[        U5      * :  a  US-  nUU   u  nn[%        U	5       Vs/ s H  oU   b  M
  X   U:w  d  M  UPM     nn[        U5      U:  a  [%        U	5       H  nSX'   M	     O5U" X5        [%        U5       H
  nUXU   '   M     U[        U5      * :  a  M  U$ M  s  snnf s  snf )a  Return a list of elements in which none are in the same positions
as they were originally. If an element fills more than half of the positions
then an error will be raised since no derangement is possible. To obtain
a derangement of as many items as possible--with some of the most numerous
remaining in their original positions--pass `strict=False`. To produce a
pseudorandom derangment, pass a pseudorandom selector like `choice` (see
below).

Examples
========

>>> from sympy.utilities.iterables import random_derangement
>>> t = 'SymPy: a CAS in pure Python'
>>> d = random_derangement(t)
>>> all(i != j for i, j in zip(d, t))
True

A predictable result can be obtained by using a pseudorandom
generator for the choice:

>>> from sympy.core.random import seed, choice as c
>>> seed(1)
>>> d = [''.join(random_derangement(t, c)) for i in range(5)]
>>> assert len(set(d)) != 1  # we got different values

By reseeding, the same sequence can be obtained:

>>> seed(1)
>>> d2 = [''.join(random_derangement(t, c)) for i in range(5)]
>>> assert d == d2
Nr   c                    > [        [        U 5      S-
  SS5       H/  nT" U SUS-    5      nU R                  U5      nX   X   sX'   X'   M1     g)zKnuth shuffler   r   r{   N)r(   r&   r   )rW   r   r4   r   choices       r    shuffle#random_derangement.<locals>.shuffleX	  sR    s2w{Ar*Ar&1q5z"AA5"%LBE25 +r,   c                    > T" U 5        U SU $ )z1shuffle rv and return the first n values
        Nr   )rW   rH   r  s     r    pick random_derangement.<locals>.pick^	  s     	"1vr,   c                     U S   $ r  r   r3   s    r    r  $random_derangement.<locals>.<lambda>e	  s    !A$r,   r  r{   r   zno derangement possible c              3   .   #    U  H  u  pX:g  v   M     g 7fr0   r   r   r   r   s      r    r!   %random_derangement.<locals>.<genexpr>	  s     0Zca16Z   r   )secretsr  ry   r&   r   rx   r=   r   rJ   reversedr   random_derangementr   rP   r   joinr'   rK   r(   )tr  strictr  r  rH  totr  r  rH   xsr   coptsstayrW   r   rd   r  s    `                @r    r  r  5	  s0   @ ~(
 
!B
a&C	
	/B rFEAAA	
2B	Av677 )!?fqVAY?Td3Bi !W$AFF1I  F+AIIaB# "1gnrwwr{4"4CG|!WBK0SZ000& I-  VAXAs2wh,Q!u1#(8K8a!u8Kt9q="1X $ &TqA"#BAwK " s2wh, 	 + @4 Ls   H;&H;?	IIIc              #   F  #    [        U 5      S:  a  g[        U 5      S:X  a  U S   U S   /v   g[        U 5      S:X  a!  U S   U S   U S   /v   U S   U S   U S   /v   g[        U 5       H2  n[        S [        X5       5       5      (       a  M%  [	        U5      v   M4     g7f)zX
yield derangements of items in ``s`` which are assumed to contain
no repeated elements
r   Nr   r   rt  c              3   .   #    U  H  u  pX:H  v   M     g 7fr0   r   r  s      r    r!   $_set_derangements.<locals>.<genexpr>	  s     0ida16ir  )r&   r   r#  rK   rJ   r   r1  s     r    r  r  	  s     
 1vz
1v{tQqTl
1v{tQqT1Q4  tQqT1Q4  !_0c!i000q'M s   B	B!B!c              #      #    [        U 5      (       d  [        U 5       Sh  vN   g[        U 5       H  n[        U5      v   M     g N%7f)a  
Return unique derangements of the elements of iterable ``s``.

Examples
========

>>> from sympy.utilities.iterables import generate_derangements
>>> list(generate_derangements([0, 1, 2]))
[[1, 2, 0], [2, 0, 1]]
>>> list(generate_derangements([0, 1, 2, 2]))
[[2, 2, 0, 1], [2, 2, 1, 0]]
>>> list(generate_derangements([0, 1, 1]))
[]

See Also
========

sympy.functions.combinatorial.factorials.subfactorial

N)rj  r  r  rJ   r  s     r    generate_derangementsr  	  s;     * A;;$Q'''&q)Aq'M * 	(s   A	A&A	c              #     ^#    US:X  a  U S:  a  gS/U -  m[        T5      v   U S:X  a  g U S-
  nTU   US-
  :X  a  US-  nUS:X  a  gTU   US-
  :X  a  M  TU==   S-  ss'   [        X-
  S-
  5       H  nTU   TXC-   S-   '   M     XS-   -  S:X  a:  U(       a&  [        U4S j[        U S-
  5       5       5      (       a  [        T5      v   M  7f)a  
A routine to generate necklaces that may (free=True) or may not
(free=False) be turned over to be viewed. The "necklaces" returned
are comprised of ``n`` integers (beads) with ``k`` different
values (colors). Only unique necklaces are returned.

Examples
========

>>> from sympy.utilities.iterables import necklaces, bracelets
>>> def show(s, i):
...     return ''.join(s[j] for j in i)

The "unrestricted necklace" is sometimes also referred to as a
"bracelet" (an object that can be turned over, a sequence that can
be reversed) and the term "necklace" is used to imply a sequence
that cannot be reversed. So ACB == ABC for a bracelet (rotate and
reverse) while the two are different for a necklace since rotation
alone cannot make the two sequences the same.

(mnemonic: Bracelets can be viewed Backwards, but Not Necklaces.)

>>> B = [show('ABC', i) for i in bracelets(3, 3)]
>>> N = [show('ABC', i) for i in necklaces(3, 3)]
>>> set(N) - set(B)
{'ACB'}

>>> list(necklaces(4, 2))
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 1),
 (0, 1, 0, 1), (0, 1, 1, 1), (1, 1, 1, 1)]

>>> [show('.o', i) for i in bracelets(4, 2)]
['....', '...o', '..oo', '.o.o', '.ooo', 'oooo']

References
==========

.. [1] https://mathworld.wolfram.com/Necklace.html

.. [2] Frank Ruskey, Carla Savage, and Terry Min Yih Wang,
    Generating necklaces, Journal of Algorithms 13 (1992), 414-430;
    https://doi.org/10.1016/0196-6774(92)90047-G

r   Nr   r{   c              3   L   >#    U  H  nTTUS S2   TSUS2   -   :*  v   M     g 7fru  r   )r   r   rQ  s     r    r!   necklaces.<locals>.<genexpr>
  s2     0bUaPQa2h2a76K1KUar#   )r   r(   r'   )rH   r   freer   r   rQ  s        @r    	necklacesr  	  s     \ 	Av!a%	
AA
(NAv
Eda!emFABw da!em 	
!	quqy!AQ4AaeaiL "A;!TS0bUZ[\_`[`Ua0b-b-b(N s   ACA8Cc                     [        XSS9$ )z>Wrapper to necklaces to return a free (unrestricted) necklace.T)r  )r  )rH   r   s     r    	braceletsr  
  s    Q%%r,   c              #   F  #    [        [        SU 5      5      n USS v   X   S:  a
  XU       X'   Om[        U S-
  SS5       HX  nX   S:w  d  M  X   S-
  n[        US-
  SS5       H  nX   U:X  d  M    O   UW-
  n[        X S-   5       H  nXU-
     X'   M       O   gM  7f)aC  
This algorithm generates oriented forests.

An oriented graph is a directed graph having no symmetric pair of directed
edges. A forest is an acyclic graph, i.e., it has no cycles. A forest can
also be described as a disjoint union of trees, which are graphs in which
any two vertices are connected by exactly one simple path.

Examples
========

>>> from sympy.utilities.iterables import generate_oriented_forest
>>> list(generate_oriented_forest(4))
[[0, 1, 2, 3], [0, 1, 2, 2], [0, 1, 2, 1], [0, 1, 2, 0],     [0, 1, 1, 1], [0, 1, 1, 0], [0, 1, 0, 1], [0, 1, 0, 0], [0, 0, 0, 0]]

References
==========

.. [1] T. Beyer and S.M. Hedetniemi: constant time generation of
       rooted trees, SIAM J. Computing Vol. 9, No. 4, November 1980

.. [2] https://stackoverflow.com/questions/1633833/oriented-forest-taocp-algorithm-in-python

r{   r   Nr   )rJ   r(   )rH   Pr1  targetr7  offsetr   s          r    generate_oriented_forestr  
  s     4 	U2q\A
e4!8qT7AD1q5!R(419TAXF"1q5!R046>! 1 UF"1!e_ V} - ) ! s   A	B! B!3.B!c                     SSK Jn  Uc  Un[        U [        XS95      nU(       d%  U SSS2   n[        U[        XRS95      n[	        XFUS9n[        U [        5      (       d  [        U5      $ U$ )as  
Return the rotation of the sequence in which the lexically smallest
elements appear first, e.g. `cba \rightarrow acb`.

The sequence returned is a tuple, unless the input sequence is a string
in which case a string is returned.

If ``directed`` is False then the smaller of the sequence and the
reversed sequence is returned, e.g. `cba \rightarrow abc`.

If ``key`` is not None then it is used to extract a comparison key from each element in iterable.

Examples
========

>>> from sympy.combinatorics.polyhedron import minlex
>>> minlex((1, 2, 0))
(0, 1, 2)
>>> minlex((1, 0, 2))
(0, 2, 1)
>>> minlex((1, 0, 2), directed=False)
(0, 1, 2)

>>> minlex('11010011000', directed=True)
'00011010011'
>>> minlex('11010011000', directed=False)
'00011001011'

>>> minlex(('bb', 'aaa', 'c', 'a'))
('a', 'bb', 'aaa', 'c')
>>> minlex(('bb', 'aaa', 'c', 'a'), key=len)
('c', 'a', 'bb', 'aaa')

r   r  Nr  r{   )r  r  r  r  r   r8   r   r   )rS   directedr   r  bestrseqrbests          r    minlexr  :
  sl    F <
{"CsN389D4R4yD."?@4C( )c225;<<r,   c                 :   / n[        U 5      n  [        U 5      /n  [        U 5      nU" XCS   5      (       a  UR                  U5        M0  UR                  U5        U/nME  ! [         a    / s $ f = f! [         a     Of = fU(       a  UR                  U5        U$ )a  Group the sequence into lists in which successive elements
all compare the same with the comparison operator, ``op``:
op(seq[i + 1], seq[i]) is True from all elements in a run.

Examples
========

>>> from sympy.utilities.iterables import runs
>>> from operator import ge
>>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2])
[[0, 1, 2], [2], [1, 4], [3], [2], [2]]
>>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2], op=ge)
[[0, 1, 2, 2], [1, 4], [3], [2, 2]]
r{   )rG   ra   StopIterationrA   )rS   rv  cyclesruneis        r    runsr  i
  s     F
s)CCyk 	cB bb'??JJrNMM#$C   	
  		 cMs"   A! A3 !A0/A03
B ?B c             #      #    US:X  a  U (       a  U /v   g[        S[        U 5      5       H&  n[        XS US-
  5       H  nU SU /U-   v   M     M(     g7f)a  Returns the partition of sequence $l$ into $n$ bins

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

Given the sequence $l_1 \cdots l_m \in V^+$ where
$V^+$ is the Kleene plus of $V$

The set of $n$ partitions of $l$ is defined as:

.. math::
    \{(s_1, \cdots, s_n) | s_1 \in V^+, \cdots, s_n \in V^+,
    s_1 \cdots s_n = l_1 \cdots l_m\}

Parameters
==========

l : Sequence[T]
    A nonempty sequence of any Python objects

n : int
    A positive integer

Yields
======

out : list[Sequence[T]]
    A list of sequences with concatenation equals $l$.
    This should conform with the type of $l$.

Examples
========

>>> from sympy.utilities.iterables import sequence_partitions
>>> for out in sequence_partitions([1, 2, 3, 4], 2):
...     print(out)
[[1], [2, 3, 4]]
[[1, 2], [3, 4]]
[[1, 2, 3], [4]]

Notes
=====

This is modified version of EnricoGiampieri's partition generator
from https://stackoverflow.com/questions/13131491/partition-n-items-into-k-bins-in-python-lazily

See Also
========

sequence_partitions_empty
r   N)r(   r&   sequence_partitionsrw  rH   r   parts       r    r  r  
  s[     j 	Av!c	1c!f'"q1u5DRa5'D.  6 s   AAc             #      #    US:  a  gUS:X  a  U /v   g[        S[        U 5      S-   5       H&  n[        XS US-
  5       H  nU SU /U-   v   M     M(     g7f)a'  Returns the partition of sequence $l$ into $n$ bins with
empty sequence

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

Given the sequence $l_1 \cdots l_m \in V^*$ where
$V^*$ is the Kleene star of $V$

The set of $n$ partitions of $l$ is defined as:

.. math::
    \{(s_1, \cdots, s_n) | s_1 \in V^*, \cdots, s_n \in V^*,
    s_1 \cdots s_n = l_1 \cdots l_m\}

There are more combinations than :func:`sequence_partitions` because
empty sequence can fill everywhere, so we try to provide different
utility for this.

Parameters
==========

l : Sequence[T]
    A sequence of any Python objects (can be possibly empty)

n : int
    A positive integer

Yields
======

out : list[Sequence[T]]
    A list of sequences with concatenation equals $l$.
    This should conform with the type of $l$.

Examples
========

>>> from sympy.utilities.iterables import sequence_partitions_empty
>>> for out in sequence_partitions_empty([1, 2, 3, 4], 2):
...     print(out)
[[], [1, 2, 3, 4]]
[[1], [2, 3, 4]]
[[1, 2], [3, 4]]
[[1, 2, 3], [4]]
[[1, 2, 3, 4], []]

See Also
========

sequence_partitions
r   Nr   )r(   r&   sequence_partitions_emptyr  s       r    r  r  
  sg     j 	1uAvc	1c!fqj!-aeQU;DRa5'D.  < "s   AAc           	   #     #    Uc  [        X5       Sh  vN   gUS:X  a1  [        U 5       H!  n[        U5      n[        X15       Sh  vN   M#     gUS:X  a  [        X5       Sh  vN   gUS:X  a2  [        X5       H"  n[	        U5       H  n[        U5      v   M     M$     gUS:X  a  [        [        U 5      USS9 H  u  pdXa:w  a  M  [        U 5       Hd  n/ nS=p[        U5      n[        UR                  5       5       H0  u  p[        U5       H  nX-   n
UR                  XyU
 5        U
n	M     M2     Uv   Mf     M     g[        SU-  5      e GN; GN N7f)	a  
Return sequence ``l`` partitioned into ``k`` bins.

Examples
========

The default is to give the items in the same order, but grouped
into k partitions without any reordering:

>>> from sympy.utilities.iterables import kbins
>>> for p in kbins(list(range(5)), 2):
...     print(p)
...
[[0], [1, 2, 3, 4]]
[[0, 1], [2, 3, 4]]
[[0, 1, 2], [3, 4]]
[[0, 1, 2, 3], [4]]

The ``ordered`` flag is either None (to give the simple partition
of the elements) or is a 2 digit integer indicating whether the order of
the bins and the order of the items in the bins matters. Given::

    A = [[0], [1, 2]]
    B = [[1, 2], [0]]
    C = [[2, 1], [0]]
    D = [[0], [2, 1]]

the following values for ``ordered`` have the shown meanings::

    00 means A == B == C == D
    01 means A == B
    10 means A == D
    11 means A == A

>>> for ordered_flag in [None, 0, 1, 10, 11]:
...     print('ordered = %s' % ordered_flag)
...     for p in kbins(list(range(3)), 2, ordered=ordered_flag):
...         print('     %s' % p)
...
ordered = None
     [[0], [1, 2]]
     [[0, 1], [2]]
ordered = 0
     [[0, 1], [2]]
     [[0, 2], [1]]
     [[0], [1, 2]]
ordered = 1
     [[0], [1, 2]]
     [[0], [2, 1]]
     [[1], [0, 2]]
     [[1], [2, 0]]
     [[2], [0, 1]]
     [[2], [1, 0]]
ordered = 10
     [[0, 1], [2]]
     [[2], [0, 1]]
     [[0, 2], [1]]
     [[1], [0, 2]]
     [[0], [1, 2]]
     [[1, 2], [0]]
ordered = 11
     [[0], [1, 2]]
     [[0, 1], [2]]
     [[0], [2, 1]]
     [[0, 2], [1]]
     [[1], [0, 2]]
     [[1, 0], [2]]
     [[1], [2, 0]]
     [[1, 2], [0]]
     [[2], [0, 1]]
     [[2, 0], [1]]
     [[2], [1, 0]]
     [[2, 1], [0]]

See Also
========

partitions, multiset_partitions

N   r   
   r   Tr;  z/ordered must be one of 00, 01, 10 or 11, not %s)r  r-  rJ   rC  r   r=  r&   r   rx   r(   rA   r=   )rw  r   r  plr1  permkgotlirW   r   r   r.  multiplicityr*   s                 r    kbinsr  
  sK    b &q,,,	B'*BbB*2111 + 
B&q,,,	B$Q*A$Q4j  ( + 
A!#a&!$7GDy+A.	"X*0*;&D"<0H		"(+ 1 +<
  / 8 =GI 	I5 	- 2,s4   EE2EEE%E&C*EEEc           	   #      #    [        S/[        U 5      U R                  S5      -
  -  6  HJ  n[        U5      n[	        U 5      " U  Vs/ s H  o"(       a  X!R                  5       -  OUPM     sn5      v   ML     gs  snf 7f)zReturn iterator in which the signs of non-zero elements
of t are permuted.

Examples
========

>>> from sympy.utilities.iterables import permute_signs
>>> list(permute_signs((0, 1, 2)))
[(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2)]
)r   r{   r   N)r   r&   countrJ   rP   r   )r  signsr   s      r    permute_signsr  z  sg      7)SVaggaj%89:U1g!<!Qq}q0!<== ;<s   AA>$A9
+A>c                 .   ^  U 4S j[        T 5       5       $ )a(  Return iterator in which the signs of non-zero elements
of t and the order of the elements are permuted and all
returned values are unique.

Examples
========

>>> from sympy.utilities.iterables import signed_permutations
>>> list(signed_permutations((0, 1, 2)))
[(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2), (0, 2, 1),
(0, -2, 1), (0, 2, -1), (0, -2, -1), (1, 0, 2), (-1, 0, 2),
(1, 0, -2), (-1, 0, -2), (1, 2, 0), (-1, 2, 0), (1, -2, 0),
(-1, -2, 0), (2, 0, 1), (-2, 0, 1), (2, 0, -1), (-2, 0, -1),
(2, 1, 0), (-2, 1, 0), (2, -1, 0), (-2, -1, 0)]
c              3   l   >#    U  H)  n[        U5        H  n[        T5      " U5      v   M     M+     g 7fr0   )r  rP   )r   r   r   r  s      r    r!   &signed_permutations.<locals>.<genexpr>  s4      # 81q!A GAJJ!  8s   14)r-  )r  s   `r    signed_permutationsr    s     # 5a 8 # #r,   c              #   v   #    [        U 5      n[        [        U5      5       H  nUv   [        X!5      nM     g7f)ac  Return a generator giving the items in s as list where
each subsequent list has the items rotated to the left (default)
or right (``dir=-1``) relative to the previous list.

Examples
========

>>> from sympy import rotations
>>> list(rotations([1,2,3]))
[[1, 2, 3], [2, 3, 1], [3, 1, 2]]
>>> list(rotations([1,2,3], -1))
[[1, 2, 3], [3, 1, 2], [2, 3, 1]]
N)rJ   r(   r&   r  )r   dirrS   r   s       r    	rotationsr    s1      q'C3s8_	## s   79c               '      #    [        S U  5       5      n[        U 5      nU(       a   U H  nU" 5       v   M     U(       a  M  gg! [         a    US-  n[        [        X5      5      n N0f = f7f)zroundrobin recipe taken from itertools documentation:
https://docs.python.org/3/library/itertools.html#itertools-recipes

roundrobin('ABC', 'D', 'EF') --> A D E B F C

Recipe credited to George Sakkis
c              3   L   #    U  H  n[        U5      R                  v   M     g 7fr0   )rG   __next__)r   rb   s     r    r!   roundrobin.<locals>.<genexpr>  s     8i$r(##is   "$r   N)r	   r&   r  r
   )rq   nextspendingnxts       r    
roundrobinr    sh      8i88E)nG
	2e  '  	2qLG&01E	2s-   %A.A A.A.#A+(A.*A++A.c                       \ rS rSrSrSrg)NotIterablei  z
Use this as mixin when creating a class which is not supposed to
return true when iterable() is called on its instances because
calling list() on the instance, for example, would result in
an infinite loop.
r   N)__name__
__module____qualname____firstlineno____doc____static_attributes__r   r,   r    r  r    s     	r,   r  c                     [        U S5      (       a  U R                  $  [        U 5        U(       a  [	        X5      (       + $ g! [         a     gf = f)a  
Return a boolean indicating whether ``i`` is SymPy iterable.
True also indicates that the iterator is finite, e.g. you can
call list(...) on the instance.

When SymPy is working with iterables, it is almost always assuming
that the iterable is not a string or a mapping, so those are excluded
by default. If you want a pure Python definition, make exclude=None. To
exclude multiple items, pass them as a tuple.

You can also set the _iterable attribute to True or False on your class,
which will override the checks here, including the exclude test.

As a rule of thumb, some SymPy functions use this to check if they should
recursively map over an object. If an object is technically iterable in
the Python sense but does not desire this behavior (e.g., because its
iteration is not finite, or because iteration might induce an unwanted
computation), it should disable it by setting the _iterable attribute to False.

See also: is_sequence

Examples
========

>>> from sympy.utilities.iterables import iterable
>>> from sympy import Tuple
>>> things = [[1], (1,), set([1]), Tuple(1), (j for j in [1, 2]), {1:2}, '1', 1]
>>> for i in things:
...     print('%s %s' % (iterable(i), type(i)))
True <... 'list'>
True <... 'tuple'>
True <... 'set'>
True <class 'sympy.core.containers.Tuple'>
True <... 'generator'>
False <... 'dict'>
False <... 'str'>
False <... 'int'>

>>> iterable({}, exclude=None)
True
>>> iterable({}, exclude=str)
True
>>> iterable("no", exclude=str)
False

	_iterableFT)r>   r  rG   r   r8   )r   r   s     r    rB   rB     sR    ^ q+{{Q a)))	  s   A 
AAc                     [        U S5      =(       a    [        U 5      =(       d    [        U5      =(       a    [        X5      $ )ar  
Return a boolean indicating whether ``i`` is a sequence in the SymPy
sense. If anything that fails the test below should be included as
being a sequence for your application, set 'include' to that object's
type; multiple types should be passed as a tuple of types.

Note: although generators can generate a sequence, they often need special
handling to make sure their elements are captured before the generator is
exhausted, so these are not included by default in the definition of a
sequence.

See also: iterable

Examples
========

>>> from sympy.utilities.iterables import is_sequence
>>> from types import GeneratorType
>>> is_sequence([])
True
>>> is_sequence(set())
False
>>> is_sequence('abc')
False
>>> is_sequence('abc', include=str)
True
>>> generator = (c for c in 'abc')
>>> is_sequence(generator)
False
>>> is_sequence(generator, include=(str, GeneratorType))
True

rq  )r>   rB   rE  r8   )r   includes     r    r1   r1     s9    D A}% QK#M #q"$r,   z
    Using postorder_traversal from the sympy.utilities.iterables submodule is
    deprecated.

    Instead, use postorder_traversal from the top-level sympy namespace, like

        sympy.postorder_traversal
    z1.10z$deprecated-traversal-functions-moved)deprecated_since_versionactive_deprecations_targetc                     SSK Jn  U" XS9$ )Nr   )postorder_traversal)rI  )sympy.core.traversalr  )r   rI  _postorder_traversals      r    r  r  3  s     Q00r,   z
    Using interactive_traversal from the sympy.utilities.iterables submodule
    is deprecated.

    Instead, use interactive_traversal from the top-level sympy namespace,
    like

        sympy.interactive_traversal
    c                     SSK Jn  U" U 5      $ )Nr   )interactive_traversal)sympy.interactive.traversalr  )expr_interactive_traversals     r    r  r  C  s     \!$''r,   z
    Importing default_sort_key from sympy.utilities.iterables is deprecated.
    Use from sympy import default_sort_key instead.
    z#deprecated-sympy-core-compatibilityc                      SSK Jn  U" U 0 UD6$ )Nr   )default_sort_key)sympyr  )r:   kwargs_default_sort_keys      r    r  r  T  s     <d-f--r,   c                      SSK Jn  U" U 0 UD6$ )Nr   r  )r  r  )r:   r  _ordereds      r    r  r  a  s     *T$V$$r,   r   )NN)r   )T)NF)F)r4   Nr   r   r0   )NNF)NTrc  )r   )Zcollectionsr   r   r   	itertoolsr   r   r   r	   r
   r   r   r   cartesoperatorr   sympy.utilities.enumerativer   r   r   sympy.utilities.miscr   sympy.utilities.decoratorr   r+   r@   rL   rR   r^   rn   rp   ry   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r%  r-  r5  r9  rC  r=  rP  r^  rj  r<  ri  ry  r|  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   rw   rB   r1   r  r  r  r  r   r,   r    <module>r     sH   9 9  
 ( 
I I ( 0";J?D69x866'T&,ECP,*^59p0+\<Tn9
4<&&odV3r>BK<\&&'T=!~1h#LL^[A|AHE)P7t02,3)lhV"Jzz^B&8?D&
+\,=^  "J:!z<!~mI`> #($(2*	 	 dK0 7t%$P  $E
G1
G1
  $EG(G(
  $@..
  $@%%r,   