
    wgc                       d dl mZmZmZ d dlmZmZmZmZm	Z	m
Z
mZmZ d dlmZ d dlmZ d dlmZmZmZ d dlmZ d dlmZ dQd	ZdRd
ZdSdZd ZdTdZd Zd Zd ZdUdZ dVdZ!dUdZ"d Z#dWdZ$d Z%dVdZ&d Z'd Z(d Z)d Z*d Z+d Z,dXdZ-d Z.d  Z/d! Z0d" Z1d# Z2dXd$Z3dXd%Z4dRd&Z5dXd'Z6d( Z7dXd)Z8dYd*Z9dZd+Z:d, Z;d- Z<d. Z=dXd/Z>d0 Z?d1 Z@d2 ZAdZd3ZBd4 ZCd5 ZDdVd6ZEd7 ZFd8 ZGd[d9ZHefd:ZId; ZJd< ZKdXd=ZLd> ZMd? ZNd\d@ZOdA ZP G dB dC      ZQeReSeQffdDZTdXdEZU edFdGdHI      dXdJ       ZV edKdGdHI      dL        ZW edMdGdNI      dO        ZX edMdGdNI      dP        ZYy)]    )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              j                  t                     \  }z
  dz  }t         fdt	        |      D              S )a  
    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   F   K   | ]  }|z      d z
  |z
     k(    yw   N ).0kijss     ^/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/utilities/iterables.py	<genexpr>z!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                 0   ddl m} ||s| S |dkD  r|dz  }nt        d|z        d }nfd}g }| D ]]  } ||      rBt        |d      rt	        ||      s|j
                  }|j                  t        ||             M|j                  |       _ |S )	ar  
    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                 "    t        | t              S N)is_sequencesetxs    r    	reduciblezflatten.<locals>.reducibleh   s    q#&&r+   c                     t        |       S r/   )
isinstance)r3   clss    r    r4   zflatten.<locals>.reduciblek   s    a%%r+   args)levelsr7   )	sympy.tensor.arrayr-   
ValueErrorhasattrr6   r8   extendflattenappend)iterabler9   r7   r-   r4   resultels     `    r    r>   r>   9   s    H -OaZaKF@6IK K {	'	& F R=r6":b)+DWWMM'"V=>MM" Mr+   c                      dk  st               z  rt        dz        t        t         fdt	              D               S )zyGroup ``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   .   K   | ]  }|d      y wr/   r   )r   r   iterns     r    r!   zunflatten.<locals>.<genexpr>   s     3Qd14a4j3s   )r%   r;   listzipr'   )rE   rF   s   ``r    	unflattenrI   {   sA     	1uD	A>BCC3%(3455r+   c                    t        t        |            }t        t        |       |      \  }}|dk  s|rt	        d      d}t        |      }dg|z  }t        t        |            D ]  }g }	|D ]}  }
t        |
t              r|	j                  | |||
z           ||
z  }0t        t        |
            }t        |
      }|	j                   |t        | |||z    |
      d                ||z  }  ||	      ||<     t        |       |      S )a  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'   r6   intr=   r?   reshape)seqhowr)   rF   remr   	containerrvr   _rvhihi_types               r    rO   rO      s   J 	GCLACHa FAs1u 2 3 	3	AS	I
B3r7^  	B"c"

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

773q!a%="#=a#@ABQ	 #1 49R=r+   c           
          |r't        |       D cg c]  \  }}t        |       c}}S t        |       D cg c]  \  }}|t        t        |            f c}}S c c}}w c c}}w )a  
    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   rG   r%   )rP   multipler(   gr   s        r    groupr[      sR    , &-cl3daa33*1#,7$!QQDG77 47s
   A A"c              #     	K   t        |       }t        |      }g }g }t               		fd}d} |||        |||       |t        |      t        |      z   k  rkt        |t        |      z
  dz   t        |            D ]  }|||z
     ||   f  |dz  } |||        |||       |t        |      t        |      z   k  rjyyw)z4Cartesian product of two possibly infinite iterablesc                 J    t        |       }|ur|j                  |       y y r/   )nextr?   )itelemsesentinels      r    r?   z_iproduct2.<locals>.append   s'    XHLLO r+   r   r   N)rE   objectr%   r'   )
	iterable1	iterable2it1it2elems1elems2r?   rF   r)   rb   s
            @r    
_iproduct2rj      s      y/C
y/CFFxH
 	
A
3
3
s6{S[(
(qV}QF4 	+A!A#;q	**	+	QsFsF s6{S[(
(s   CCCc               '     K   t        |       dk(  rd yt        |       dk(  r| d   D ]  }|f 	 yt        |       dk(  rt        |  E d{    y| d   | dd }}t        |t        |       D ]  \  }}|f|z     y7 2w)a  
    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%   rj   iproduct)	iterablesra   firstothersefeos         r    rl   rl      s     8 9~	Y1	1 	A$J		Y1	y)))!!imv &(9: 	FB%"*	 	*s   ABB 3Bc                 F    t        t        |       j                               S )a5  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)rP   s    r    multisetru      s    " ""$%%r+   c                      dk  rt        d      t                |d}nG	 t        |      } j                         |kD  r(t        dj                   j                                     |sO|dk\  r3t	               dd j                  |d      D cg c]  }|dk(  rd	nd c}S t        t        d       d
      S |dk\  rt	               dd j                  |d      S  fdt        d z        D        S # t         $ r d}Y w xY wc c}w )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   Z   K   | ]"  }t        |      d d j                  d       $ yw)r   Nrx   )binrjust)r   r   rF   s     r    r!   zibin.<locals>.<genexpr>{  s(     BCF12J$$Q,Bs   (+)r;   r   
bit_lengthformatr|   r}   
variationsr'   )rF   bitsstrr   s   `   r    ibinr   6  s   X 	1u;<<q	A|	C$<D ||~$ *11!,,.AC C 1925a&*2B2B42MNQcAq(NNeAhd;;19q6!":##D#..BeAqDkBB!  	D	 Os   C4 D4DDc                     |s0t        |       } t        |       |k  rt        d      S t        | |      S |dk(  rt        d      S t	        | |      S )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%   rE   r   r   )rP   rF   rz   s      r    r   r   ~  sP    F Cjs8a<8OC##6;3q))r+   c                     |h|s3t        j                   fdt        t               dz         D              S t        j                   fdt        t               dz         D              S |st	         |      S t         |      S )a0  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   6   K   | ]  }t        |        y wr/   r   r   r   rP   s     r    r!   zsubsets.<locals>.<genexpr>  s"      (F,- )5S!(< (F   r   c              3   6   K   | ]  }t        |        y wr/   )r   r   s     r    r!   zsubsets.<locals>.<genexpr>  s#      (F,- )Fc1(M (Fr   )r   from_iterabler'   r%   r   r   )rP   r   rz   s   `  r    subsetsr     s    T 	y&& (F16s3x!|1D(F G G && (F16s3x!|1D(F G G Q''0a88r+   c              #   B   K   t        |      }| D ]  }||vs|  yw)a,  
    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)r1   )iteratorexcluder   s      r    filter_symbolsr     s-     & 'lG GGs   c              /   ~   K   t        |xs g       }|ddlm} |}	 | |} ||g|i |}||vr| |dz  } w)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   )r1   
sympy.corer   )	prefixr7   startr   r8   assumptionsr   namer   s	            r    numbered_symbolsr     sa     > '-R G
{ 	&
'+t+{+GG
 s   ;=c                     ddl m} ddl}|j                  } |       x|_        }	  |         ||_        |j	                         S # ||_        w xY w)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   +  sI    $ ZZF 
"CJ
==? 
s   A 	Ac                    |s2t        t              }| D ]  }| ||         j                  |        |S g g fx}\  }}| D ]  }	 | ||         j                  |        ||fS # t        t        f$ r t        d      w xY w)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   rG   r?   
IndexError	TypeErrorr;   )rP   keyfuncbinaryr)   r   siftFTs           r    r   r   I  s    R  	$AgajM  #	$b&D41a ?	?##A&?
 a4K I& 	?=>>	?s   A$$A?c                 ^    t        t        |      |       D cg c]  \  }}|	 c}}S c c}}w )z+Return ``n`` items from ``iter`` iterator. )rH   r'   )rE   rF   r(   values       r    taker     s%    #&uQx#68xq%U888s   )c                  :    i }| D ]  }|j                  |        |S )z-Merge dictionaries into a single dictionary. )update)dictsmergedrs   s      r    
dict_merger     s)    F d Mr+   c            	           t               sg S t               dk(  r d   S dt        t        d  D                    D ]+  t         fdt        t                     D              r+ n dz   d   d S )al  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   2   K   | ]  }t        |        y wr/   r%   r   r   s     r    r!   z common_prefix.<locals>.<genexpr>  s     ,!s1v,   c              3   @   K   | ]  }|      d       k(    ywr   Nr   r   r   r   seqss     r    r!   z common_prefix.<locals>.<genexpr>  &     F471:a+F   Nr&   r%   r'   minr   r   s   `@r    common_prefixr     s~     t9		TaAw	A3,t,,- FU3t95EFF 	
Q72A;r+   c            	          t               sg S t               dk(  r d   S dt        dt        d  D               dz
  d      D ]+  t         fdt        t                     D              r+ n dz  dk(  rg S  d   dz   d S )af  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   rw   c              3   2   K   | ]  }t        |        y wr/   r   r   s     r    r!   z common_suffix.<locals>.<genexpr>  s     1qCF1r   c              3   @   K   | ]  }|      d       k(    ywr   r   r   s     r    r!   z common_suffix.<locals>.<genexpr>  r   r   Nr   r   s   `@r    common_suffixr     s     t9		TaAw	A21D111A5r: FU3t95EFF 	
QBw	Awq1uvr+   c              #   V   K   t        |       }t        |      D ]  }| d|dz      yw)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'   rP   rF   r   s      r    prefixesr     s4      	CA1X &1q5ks   ')c              #   \   K   t        |       }t        |      D ]  }| ||z
  dz
  d   yw)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     s8      	CA1X !a%!)*os   *,c                    | \  }}g }t        |      }t        |      }|j                  d |D               |d }t        ||d      }|r|j	                         }|j                  |       t        |      D ]|  \  }}||k(  s|j                  ||f       |D ]  \  }	}
||
k(  s /  ||      }t        |      D ]&  \  }} ||      }||kD  s|j                  ||        k |j                  |       ~ |r|rt        d      |S )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   &   K   | ]	  \  }}|  y wr/   r   )r   vus      r    r!   z#topological_sort.<locals>.<genexpr>Z  s     (da(   c                     | S r/   r   )r   s    r    keyztopological_sort.<locals>.key]  s    Lr+   T)r   reversezcycle detected)
r1   rG   difference_updatesortedpopr?   remove	enumerateinsertr;   )graphr   VELSnoder   r   _u_vkvr   r   kss                  r    topological_sortr     s!   N DAq
AAAQA(a((
{	 	qc4(A
uuw	G 	$DAqDy!Q  $FBBw$ QB )! $1 V7HHQN!$ #	$	 . 	)**r+   c                     | \  }}|D ci c]  }|g  }}|D ]  \  }}||   j                  |        t        ||      S c c}w )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

    )r?   _strongly_connected_components)Gr   r   viGmapv1v2s          r    strongly_connected_componentsr     sZ    d DAqrBFD BR)!T22  s   
A c                 0  	
 i i t               g 	g 
t               }	fd}	
fd}| D ]\  }|v r ||       	s	d   \  }}t        ||      }||u r	 ||       n&|vr	 ||       n|v rt        |   |         |<   	rJ^ 
S )zAMore efficient internal routine for strongly_connected_componentsc                 x    t              }|x| <   | <   d | <   j                  | t        |          f       y r/   )r%   r?   rE   )r   indexr   	callstackr$   lowlinkstacks     r    r   z-_strongly_connected_components.<locals>.start  sB    E
"''
WQZa!T$q']+,r+   c                 :   |    |    k(  r\j                         d   g}|d   | ur*|j                  j                         d          |d   | ur*j                  |d d d          j                         \  }}rd   \  } }t        |    |         | <   y y )Nr   rw   )popitemr?   r   r   )	r   	componentr   r(   r   
componentsr$   r   r   s	       r    finishz._strongly_connected_components.<locals>.finish  s    2;'"+%+,IB-r)  !34 B-r)i"o.AbMEBgbk72;7GBK r+   rw   )r   rc   r^   r   )r   r   nomorer   r   r   r   rf   r   r   r   r$   r   r   s    `       @@@@@r    r   r     s    ( GGMEIJXF- -
8 
8  <<amGBc6"BV|r
7"b	u!'"+wr{; 	<" r+   c                 l    | \  }}g }|D ]  \  }}|j                  ||f||fg        t        ||f      S )a  
    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     sQ    N DAqL 2Bb"XBx012(!\):;;r+   c                 T    t        |       dk(  rg S |t        |       z  }| |d | d| z   S )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   r3   ys     r    rotate_leftr   g  s7     1v{		CF
AQR51Ra5=r+   c                 l    t        |       dk(  rg S t        |       |t        |       z  z
  }| |d | d| z   S )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QR51Ra5=r+   c                    ddl m} ||}| | z   }dgt        |      z  }d}t        dt        |            D ]  }||   }|||z
  dz
     }|dk7  rI||||z   dz      k7  r; ||       ||||z   dz            k  r||z
  dz
  }||   }|dk7  r||||z   dz      k7  r;||||z   dz      k7  r ||       |||         k  r|}d|||z
  <   |dz   |||z
  <    |S )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   Idrw   r   )(sympy.functions.elementary.miscellaneousr  r%   r'   )	r3   r   r  r   fr   r   sjr   s	            r    least_rotationr	    s   * <
{"C	AA	s1vA	A1SV_ qTac!eH2g"!A#a%.2wQqs1uX&aCE!A 2g"!A#a%. 1Q3q5>2wQqT"AacFqSAacF Hr+   c           	   #   f  K   ddl m} |t        | t              ret	        d | j                         D              rt        d      t        | j                               }||kD  ry ||       D cg c]	  }|| |   g }}nBt        |       } t        |       }||kD  ry	 t        |       }  ||       D cg c]	  }|| |   f }}~ nt        d |D              }||kD  s|sg  yt        |      D ]m  \  }\  }}||k\  r|g|z   |d	z
  }t        t        ||      dd
      D ]9  }t!        d||z
  ||d	z   d       D ]  }|g|z  |z   }	t        |	      |k(  s|	   ; o yc c}w c c}w # t        $ r= t         ||             } t        | d      D cg c]  }t        |       nc c}w }}Y w xY ww)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   8   K   | ]  }t        |      d k    ywr   r   r   r   s     r    r!   z(multiset_combinations.<locals>.<genexpr>       5Q6!9q=5   counts cannot be negativeFrY   c              3   &   K   | ]	  \  }}|  y wr/   r   r   r   r   s      r    r!   z(multiset_combinations.<locals>.<genexpr>  s      da r   r   rw   )sympy.core.sortingr  r6   rs   anyvaluesr;   rK   rG   r%   ru   r   r[   r   r'   r   multiset_combinations)
r)   rF   rZ   r  Nr   r   r   r   rT   s
             r    r  r    s    4 +ya5!((*55 !<==AHHJA1u$+AJ/q!QqT/A/QAAA1u@QK(/
31a1Y33   a  1uA"1 	!IAv1Avc!eE3q!9a, !.tQUAa!efIF !AQB2w!| !!		!' 0 4 @$&+A&>?T!W???@s[   A-F1/E=F1E( 2E# E( BF1F1#E( ()F.F$#F.+F1-F..F1c              #     K   ddl m} |t        | t              rFt	        d | j                         D              rt        d       ||       D cg c]	  }|| |   g }}n4t         ||             } t        | d      D cg c]  }t        |       }}~ |D cg c]  }|d   dkD  s| }}t        d	 |D              }|r|||kD  s|dk  r|s||dk(  rg  y|dk(  r|D ]
  \  }}	|g  yt        |      dk(  r1|d   \  }}	||	n||	k  r|nd}	t        |	      D cg c]  }| c} yt        d
 |D              r2t        |D 	cg c]  \  }}	|	 c}	}|      D ]  }
t        |
        y||n|}t        |      D ]H  \  }\  }}	||   dxx   dz  cc<   t        d|dz
  |      D ]  }|s|g|z     ||   dxx   dz  cc<   J yc c}w c c}w c c}w c c}w c c}	}w w)aw  
    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   8   K   | ]  }t        |      d k    ywr   r   r  s     r    r!   z(multiset_permutations.<locals>.<genexpr>	  r  r  r  Fr  r   c              3   &   K   | ]	  }|d      ywr   r   )r   gis     r    r!   z(multiset_permutations.<locals>.<genexpr>  s     !be!r   c              3   ,   K   | ]  \  }}|d k(    ywr   r   r  s      r    r!   z(multiset_permutations.<locals>.<genexpr>  s     #1Q!V#   )r  r  r6   rs   r  r  r;   rG   r[   rK   r%   r'   r&   r   r   multiset_permutations)r)   sizerZ   r  r   r   r  doSUMr   pr   s               r    r   r     s      +ya5!((*55 !<==$+AJ/q!QqT/A/WQZ A"'E":;Qa;A;	&BqEAI"	&B	&
!b!
!C!tczTAXdldaiH	 	DAq#I		RA!u1ADAID1(#Qq##	##	#R0TQq0$7 	Aq'M	 'tS"2 	IAv1qE!HMH*42> "#'M" qE!HMH	/ 0 <	& $0sP   AG+G#G+GG+G(G,A5G+!	G *"G+G%
AG+47G+c                     |t        |      dz   }nt        |t              r||}}t        |      D cg c]  }g  }}t	        |      D ]  \  }}||   j                  | |           |S c c}w )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   )maxr6   rN   r'   r   r?   )rP   vectorr)   r   r$  r   s         r    
_partitionr(  *  sv    8 	yK!O	FC	 v1XA&! 1	!CFH 	s   	A*c              #   6  K   dg| z  }dg| z  }d}||f || k7  r|| }	 |dz  }||   }||   dk7  rnd||<   |dz  }|||<   |dz  }||| z
  z  }|dxx   | |z
  z  cc<   ||k(  r
d||<   |dz  }||dz
  xx   dz  cc<   ||xx   dz  cc<   ||f || k7  r{yyw)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   )rF   r$  qncr)   r   s         r    _set_partitionsr,  P  s     l 
AA	
AA	
B
a%K
'FA!AtqyAaD  	
Q!	Q
a!e	!A7AbE!GB	!a%A	!	!e% 's   BBBc           
   #   &  K   t        | t              r| }|r||kD  ryt        t        |            } |dk(  r	| dd g yt	        |      D ]S  \  }}|||k(  st        |      D cg c]  }g  }}t        |      D ]  }|||      j                  | |           | U yt        |       dk(  rt        | t              r| g} t        |       svt        |       }|r||kD  ry|dk(  r	| dd g y| dd }t        ||d      D ]>  \  }}	|||k(  sg }t        |	      D ]  }
|j                  ||
z  g|	|
   z          | @ yddlm} t         ||             } t        |       }|r||kD  ry|dk(  r	| dd g yt        t        | d       \  }}t        |      t        |       k  rU|r4t!               }|j#                  ||dz
  |      D ]  }t%        ||        yt'        |      D ]  }t%        ||        yt	        |      D ]q  \  }}|||k(  st        |      D cg c]  }g  }}t        |      D ]  }|||      j                  |        |D cg c]  }|D cg c]  }| |   	 c} c}} s yc c}w c c}w c c}w c c}}w w)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)r6   rN   rG   r'   r,  r?   r%   r   has_variety
partitionsr   r=   r  r  rH   r[   r   
enum_ranger   r   )ru   r)   rF   r+  r*  r   rT   r3   r!  r$  r   r  elementsmultiplicitiesmptstater   s                    r    multiset_partitionsr6    s    Z (C Qa>6A;- %Q' 	EByB!G"'),Qb,,q 1AqtHOOHQK01	 	
8}j37:x  MQ6A;-RaL!!QT2 	GD!yDAI *AIIqseAaDj)*	 	/)*MQ6A;-
 $'h(>#? .x=3x=( 02 ^^NAaCC 8E&uh778 7~F 8E&uh778 )+ AA9a&+Bi0"0B0"1X +1Q4*+=?@3AHQK3@@Ao -r 1 4@sV   AJJ%	I<.B JDJJ"	J+.J	J"J.J3JJJc              #     K   | dk  s||dk  s||dk  s|r|r||z  | k  r|rdi f yi  y|| }nt        ||       }t        |xs | |       }t        |       t        |      t        |      }}} t        | |      \  }}||i}|g}|rd||<   |j                  |       ||z
  t	        |      z
  }|r,t        |j                               |j                         f n|j                          |dgk7  r|d   dk(  r|d= |j                  d      }	||	z  }nd}		 |d   }
||
   dz
  x}||
<   |	|
z  }	|dk(  r|d= ||
= |dz  }|
dz  }
t        |	|
      \  }}|t	        |      z   }||kD  r|syS|||
<   |j                  |
       |rd||<   |j                  |       	 ||z  }|r,t        |j                               |j                         f n|j                          |dgk7  ryyw)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   rw   )	r   r   rL   r?   boolrK   r  copyr   )rF   r)   r   r!  r*  rmskeysroomreuser   newcountneeds                r    r0  r0  =  s%    v 	
Q	!a%	!a%	aAaC!G R%K 	 Hy1IAFAAQiF1I!qA!Q<DAq
QB3D1Aq547?D"))+	))ggi
1#+8q=RFF1IEEMDE RA!!uqy(Hr!uQJE1}HbeAID FA%#DAqtAw;Dd{BqEKKN1Abiik"BGGI--'')OM 1#+s   G&G+)G+c              #     K   | dk  s|
|dk  rg  y|dg| z  }d}| }|dkD  ry|dz  }||   dz   }|d|z  k\  r|||<   ||z  }|dz  }|d|z  k\  r|dz   }||k  r$|||<   |||<   |d|dz     |dz  }|dz  }||k  r$||z   ||<   ||   dz
  }|d|  |dkD  rxyy|dk(  r| g y| |k(  r	dg| z   yt        d| |z  dz         D ]  }|g|z  }| ||z  z
  }|s|s| |sH||k  rCt        |d      D ]2  }	t        |	      }
|	D cg c]  }||z   	 c}||
 d | |g|
z  ||
 d 4 et        d|      D ]:  }
t        ||
d      D ]'  }	|	D cg c]  }||z   	 c}||
 d | |g|
z  ||
 d ) <  yc c}w c c}w w)	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   Nrw   r   r   F)sortT)r'   ordered_partitionsr%   )rF   r)   rB  ar   r   r3   wbaxmir   s               r    rC  rC    s<    \ 	1u!a% y
 CE!eFA!qAq1u*!QQ q1u* AAq&!!QiQQ q& q5AaD!qABQ%K! !e" 
ac		
ac!e q!Q$(# 	)AAAAaCAGa1f,QU; %BRB.01q1u1ArcdGG c"fArcdG	%  1+ )B0BTB )24"5Q1q5"52#$#$#b&2#$))	) 2 #6s7   AF-F FAF +FE;<FF 
&Fc              #     K   ddl m}m} t        d | ||             z        }d}g }|r&||z   | k  r|j	                  |       ||z  }|dz  }|r&t        |      dz
  | dz  z
  }|dk\  r| ||   dk(  rd||<   |j	                  d       |dz  }-|j	                  d       ||xx   dz  cc<   ||   x}||dz   <   |dz  }|dkD  r3|t        |      |z
  dz
  k  r|| dz   d= |dz  }|||<   n|dz  }|dkD  r3|dk\  rdg| z   yw)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)mathrJ  rK  rN   r?   r%   )rF   rJ  rK  poweracc	partitionlast_numr3   s           r    binary_partitionsrQ  I  s]    4  DaM"#E
CI
;!U#5LC!	  9~!QU+H
a-X!#"#IhQMH(!&/&99Ihl#A!eC	NX-11qb1fg&A&'	(#a !e a-$ #a%Ks   AD	B(D	:D	 	D	c           	          ddl m} ddlm} t	        | t
        t        ||f      ryt               	 t        fd| D              S # t        $ r, t        |       t        t        t        |                   k7  cY S w xY w)a'  Return 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   N   K   | ]  }|v sj                  |      sd   ywTN)add)r   r   uniques     r    r!   zhas_dups.<locals>.<genexpr>  s!     EAVvzz!}4Es   %%)sympy.core.containersrS  sympy.sets.setsrT  r6   rs   r1   r  r   r%   rG   uniq)rP   rS  rT  rX  s      @r    has_dupsr\    si     +##c4-.UF0EEEE 03x3tDI///0s   A 2A;:A;c                 H    t        |       D ]  \  }}|dk(  r|}|k7  s y y)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   )rP   r   r   rb   s       r    r/  r/    s6     # 16HH} r+   c              #      K   	 t                fd}	 t               }|xs g }t               D ]'  \  }}||v r|j	                  |      r|  |        ) y# t        $ r dY Zw xY w# t        $ ra |vr|  |        |j                  |       t         d      rt         dz   d |      E d{  7   Y yt         |      E d{  7   Y yw xY ww)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                  >     t               k7  rt        d      y y )Nz&sequence changed size during iteration)r%   RuntimeError)rF   rP   s   r    checkzuniq.<locals>.check  s'     =SX]GHH +=r+   __getitem__r   )r%   r   r1   r   rW  r?   r<   r[  )rP   rA   ra  seenr   r   rF   s   `     @r    r[  r[    s     4HI)u2cN 	DAqI!	    )F?GGMM!3&CAK000C((()sz   CA C%A/ A/ A/ CA,)C+A,,C/A
C9B<:C?CCCCCCCc              #     K   t        |       } | dk  rt        d      | dk(  rd y	| dk(  r	d d y	| dk(  rg dE d	{    y	| dz
  }d
gdg|z  z   }t        t        |             }	 t	        |       d}t        |       D ]  }||   s	||   |d   kD  s|||   f} |\  }}|y	|||   z   }||   ||   c||<   ||<   ||   ||   c||<   ||<   |d
k(  s||k(  s||||   z      ||   kD  rd
||<   t        |      D ]  }||   ||   kD  sd||<    t        |dz   |       D ]  }||   ||   kD  sd||<    7 w)a7
  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   rw   Nrw   )r   r;   rG   r'   r   )rF   r)   oplbigr   r(   r   s           r    generate_bellrj    s    B 	q	A1u788Av
	
a	
aUUUESB46\qN(NC1X "a5QqTCF]QqT'C" DAqyBqE	A1qtJAaD!A$a5"Q%LBqE2a5 Ava1QAY<!A$#611X Q4!A$;BqE 1q5!_ Q4!A$;BqE/  	Vs,   A D?D=AD?D?A4D?$D?5	D?c              #      K   t        t        |             }t        |      D ]  }|D ]  }|||      |k7  s  |  yw)a  
    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)rG   r'   r   )rF   idxr$  r   s       r    generate_involutionsrm  S  sQ     8 uQx.C#  	A1w!|	 Gs
   3A 
A c           
   #      K   ddl m} 	 t               }t        |j                               }	t               |	dz  kD  ryt        |      k(  rt               E d{    y|D ]  }
||
   |	k(  s n t              D cg c]  } |   
k7  s| }}t              D cg c]  } |   
k(  s| }}dgz  d|	z  k(  rT|D ]  }
|<   	 t        |D cg c]  } |   	 c}      D ]  }t        ||      D ]
  \  }}||<     ! dgz  dd yd|	z  z
  dk(  rt        |j                               |	z
  dz   k(  rt        |      D ]  \  }}|d| ||dz   d z   }|D ]  }
|<   	 t!        |D cg c]  } |   	 c}      D ]C  } |   |<   t        ||      D ]
  \  }}||<    |}|D ]  }|   |   c|<   |<    |} E  dgz  dd y fd fdfdt#        |j%                         d	 
       t              dz
        E d{    dgz  dd y# t        $ r| t	        t         |t                                 }g } D ]$  }|D ]  }||   |k(  s|j                  |        $ & t        |      D ]  }|D cg c]  }||   	 nc c}w c}  Y yw xY w7 bc c}w c c}w c c}w c c}w 7 w)a  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   R  K   d   d   } d   d   }d   d   }d   d   }g }g }g }t        t                    D ]M  }
|   	|   | k(  r|j                  |       #|   |k(  r|j                  |       =|j                  |       O t        |      |kD  st        |      |kD  ry|D ]  }| 
|<   	 |D ]  }|
|<   	 t        ||t        |      z
        D ]0  }|D ]  }	| 
|	<   	 |D ]  }
|   	|
|<    
 |D ]  }d
|<   	 2 |D ]  }d
|<   	 |D ]  }d
|<   	 yw)zmPlace the last two elements into the partially completed
        derangement, and yield the results.
        r   r   N)r'   r%   r?   r   )rD  a_ctrF  b_ctforced_aforced_b	open_freer   a_placea_posrT   r   r   s             r    finish_derangementsz2multiset_derangements.<locals>.finish_derangements  s    
 GAJAwqzGAJAwqz 	s1v 	(A!u}Q419OOA&qTQYOOA&$$Q'	( x=43x=4#7 	ABqE	 	ABqE	#Itc(m/CD 		G  5	 a5=BqE H 1		  	ABqE	 	ABqE	s   AD'B-D'52D'c                 ^    t              D cg c]  }|   	|   | k7  s| c}S c c}w r/   )r'   )r   r   rF   rT   r   s     r    iopenz$multiset_derangements.<locals>.iopen	  s/     !8Car!u}1CCCs   
***c              3      K   | dk(  r        E d {    y 	|    \  }}t         |      |      D ]-  }|D ]  }||<   	  | dz
        E d {    |D ]  }d |<   	 / y 7 P7 wNr   r   )
r   Mmxr   iir"  rw  ry  rT   r   s
        r    r"  z!multiset_derangements.<locals>.do	  s     6 +,,, GEAr!%(B/ 	" BBrF a!e9$$  "B!BrF"	" - %s!   A(A$<A(A&A(&A(c                     | d   | d   fS )Nr   r   r   r2   s    r    <lambda>z'multiset_derangements.<locals>.<lambda>0	  s    AaD!A$< r+   r   )r  r  ru   r   rs   r   r[  r?   multiset_derangementsr&  r  r%   _set_derangementsr'   r   rH   r   r   rt   )r   r  r;  r   hsir   r   r   r}  r|  inonMiMr$  pii1ifillr"  rw  ry  rF   rT   r   s   `                @@@@@@r    r  r  x  sn    & +a[ 
RYY[	BAA 
!tax 2w!|$Q'''  a5B; a.1AaDAIQ.E.1X	+1!	+B	+
B 	tqy 	ABqE	 'e'<!'<= 	AR 21H	
 q1 	1R4x1}RYY[)QVaZ7u% 	EAr"1Iacd+E 1!"7A1Q4"78 22 QZ EArBqE A#%a5"Q%LBqE2a5HA		 q1/bD" "* "((*"78D#d)a-   F1HBqEE  9WT!W-./ 	B q6R<HHQK	
 'q) 	&A#$%a3q6%%%	&2 	( /	+ (=" #8D !s   K H? A	K %K&K 9K 	K
K
K *K8K<%K !K-BK K
B#K 0K1K ?A K (K(J54KK KK 
K c                 T   ddl }|j                  fdfd}t        |       }t        |       }t	        |j                         d       }|d   \  }}t        |       }	d|z  |z
  }
|
dkD  r|rt        d	      t        |       D cg c]  \  }}||d   d   k(  s| }}} |||
       t	        |d|
       }t        |       }t        |      D ]  }|j                  |        t        |      }|D ]  }|j                  ||d   d           t        |       t        u rd
j                  |      S |S |	t        |      k(  r4t        |       }	  |       t!        d t#        ||       D              r	 |S (dg|	z  }	 d}|t        |       kD  r|dz  }||   \  }}t%        |	      D cg c]  }||   	| |   |k7  s| }}t        |      |k  rt%        |	      D ]  }d||<   	 n3 |||       t%        |      D ]
  }||||   <    |t        |       kD  r|S c c}}w c c}w )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                     t        t        |       dz
  dd      D ]2  } | d|dz          }| j                  |      }| |   | |   c| |<   | |<   4 y)zKnuth shuffler   r   rw   N)r'   r%   r   )rT   r   r3   r   choices       r    shufflez#random_derangement.<locals>.shuffleX	  s_    s2w{Ar* 	(Ar&1q5z"AAa5"Q%LBqE2a5	(r+   c                      |        | d| S )z1shuffle rv and return the first n values
        Nr   )rT   rF   r  s     r    pickz random_derangement.<locals>.pick^	  s     	"1vr+   c                     | d   S r{  r   r2   s    r    r  z$random_derangement.<locals>.<lambda>e	  s
    !A$ r+   r  rw   r   zno derangement possible c              3   ,   K   | ]  \  }}||k7    y wr/   r   r   r   r   s      r    r!   z%random_derangement.<locals>.<genexpr>	  s     0ca160r  r   )secretsr  ru   r%   r   rt   r;   r   rG   reversedr   random_derangementr   rM   r   joinr&   rH   r'   )tr  strictr  r  r;  totr|  r}  rF   xsr   coptsstayrT   r   ra   r  s    `                @r    r  r  5	  sU   @ ~(
 
!B
a&C	
	/B rFEArAA	
2B	Av677 )!?fq!RVAY??T2d3Bi !W$ 	AFF1I	F+ 	$AIIaB#	$"1gnrwwr{4"4CG|!WBK0SQZ00& I-  VAXAs2wh,Q!u1#(8Kar!u}1KKt9q="1X % $1%T1q $A"#BtAwK$ s2wh, 	 + @4 Ls   H H-
H%8H%H%c              #   2  K   t        |       dk  ryt        |       dk(  r| d   | d   g yt        |       dk(  r!| d   | d   | d   g | d   | d   | d   g yt        |       D ],  }t        d t        ||       D              r t	        |       . yw)zd
    yield derangements of items in ``s`` which are assumed to contain
    no repeated elements
    r   Nr   r   re  c              3   ,   K   | ]  \  }}||k(    y wr/   r   r  s      r    r!   z$_set_derangements.<locals>.<genexpr>	  s     0da160r  )r%   r   r  rH   rG   r   r$  s     r    r  r  	  s     
 1vz
1v{tQqTl
1v{tQqT1Q4  tQqT1Q4  !_ 0c!Qi00q'Ms   BBBc              #      K   t        |       st        |       E d{    yt        |       D ]  }t        |        y7 #w)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)r\  r  r  rG   r  s     r    generate_derangementsr  	  s?     * A;$Q'''&q) 	Aq'M	 	(s   AA $Ac              #   |  K   |dk(  r| dkD  rydg| z  t               | dk(  ry	 | dz
  }|   |dz
  k(  r|dz  }|dk(  ry|   |dz
  k(  r|xx   dz  cc<   t        | |z
  dz
        D ]  }|   ||z   dz   <    | |dz   z  dk(  r/|r t        fdt        | dz
        D              rt               w)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   rw   c              3   F   K   | ]  }|d d   d|d   z   k    y wrf  r   )r   r   rD  s     r    r!   znecklaces.<locals>.<genexpr>
  s0     0bPQa2h2a76K1K0br"   )r   r'   r&   )rF   r   freer   r   rD  s        @r    	necklacesr  	  s     \ 	Av!a%	
AA
(NAv
Eda!emFABw da!em 	
!	q1uqy! 	 AQ4Aa!eaiL	 A;!TS0bUZ[\_`[`Ua0b-b(N s   AB<A,B<c                     t        | |d      S )z>Wrapper to necklaces to return a free (unrestricted) necklace.T)r  )r  )rF   r   s     r    	braceletsr  
  s    Q%%r+   c              #   D  K   t        t        d|             }	 |dd  ||    dkD  r|||       || <   nkt        | dz
  dd      D ]W  }||   dk7  s||   dz
  }t        |dz
  dd      D ]  }||   |k(  s n |z
  }t        || dz         D ]  }|||z
     ||<     n yw)a  
    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

    rw   r   Nr   )rG   r'   )rF   Pr$  targetr*  offsetr   s          r    generate_oriented_forestr  
  s     4 	U2q\A
eQ4!8QqT7AaD1q5!R( Q419qTAXF"1q5!R0 "Q46>!" UF"1a!e_ - V}!- ! s   AB #B 4,B c                     ddl m} ||}t        | t        | |            }|s-| ddd   }t        |t        ||            }t	        |||      }t        | t              st        |      S |S )a  
    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  rw   )r  r  r   r	  r   r6   r   r   )rP   directedr   r  bestrseqrbests          r    minlexr  :
  so    F <
{"CsN3C89D4R4yD.3"?@4C( )c25;<<r+   c                     g }t        |       } 	 t        |       g}	 	 t        |       } |||d         r|j                  |       +|j                  |       |g}?# t        $ r g cY S w xY w# t        $ r Y nw xY w|r|j                  |       |S )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]]
    rw   )rE   r^   StopIterationr?   )rP   rg  cyclesruneis        r    runsr  i
  s     F
s)CCyk 	cB b#b'?JJrNMM#$C   	
  		 cMs"   A A, A)(A),	A87A8c             #      K   |dk(  r| r| g yt        dt        |             D ]$  }t        | |d |dz
        D ]  }| d| g|z     & yw)az  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rh  rF   r   parts       r    r  r  
  sh     j 	Av!c	1c!f !'!"q1u5 	!DRa5'D. 	!!s   AAc             #      K   |dk  ry|dk(  r| g yt        dt        |       dz         D ]$  }t        | |d |dz
        D ]  }| d| g|z     & yw)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  
  st     j 	1uAvc	1c!fqj! !-aeQU; 	!DRa5'D. 	!!s   AAc           	   #     K   |t        | |      E d{    y|dk(  r0t        |       D ]!  }t        |      }t        ||      E d{    # y|dk(  rt        | |      E d{    y|dk(  r/t        | |      D ]  }t	        |      D ]  }t        |        ! y|dk(  rt        t        |       |d      D ]|  \  }}||k7  rt        |       D ]c  }g }dx}	}
t        |      }t        |j                               D ]0  \  }}t        |      D ]  }|	|z   }
|j                  ||	|
        |
}	 2 | e ~ yt        d|z        7 37 7 w)	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   rG   r6  r   r0  r%   r   rt   r'   r?   r;   )rh  r   r  plr$  permkgotlirT   r   r   r!  multiplicityr)   s                 r    kbinsr  
  s    b &q!,,,	B'* 	2BbB*2q111	2 
B&q!,,,	B$Q* 	!A$Q !4j !	! 
A!#a&!$7 	GD!qy+A. 		A"X*0*; &D,"<0 H		"Q(+
 		 =GI 	I5 	- 2,s4   EE2EE
E#E$C$E
EEc           	   #      K   t        dgt        |       | j                  d      z
  z   D ]C  }t        |      } t	        |       | D cg c]  }|r||j                         z  n| c}       E yc c}w w)a  Return 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   rw   r   N)r   r%   countrG   rM   r   )r  signsr   s      r    permute_signsr  z  sm      7)SVaggaj%89: >Ud1g!<Qq}q0<==><s   AA6A1
%A6c                 ,      fdt               D        S )aX  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   `   K   | ]%  }t        |      D ]  } t              |        ' y wr/   )r  rM   )r   r   r   r  s      r    r!   z&signed_permutations.<locals>.<genexpr>  s9      #1q!# DGAJ #J #s   +.)r   )r  s   `r    signed_permutationsr    s     # 5a 8 # #r+   c              #   t   K   t        |       }t        t        |            D ]  }| t        ||      } yw)a  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)rG   r'   r%   r   )r   dirrP   r   s       r    	rotationsr    s9      q'C3s8_ $	#s#$s   68c               '      K   t        d | D              }t        |       }|r	 |D ]  } |         	 |ryy# t        $ r |dz  }t        t        ||            }Y *w xY ww)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   F   K   | ]  }t        |      j                    y wr/   )rE   __next__)r   r_   s     r    r!   zroundrobin.<locals>.<genexpr>  s     8$r(##8s   !r   N)r	   r%   r  r
   )rm   nextspendingnxts       r    
roundrobinr    sn      8i88E)nG
	2 e   	2qLG&01E	2s*    A"9 A"A"#AA"AA"c                       e Zd ZdZy)NotIterablez
    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.
    N)__name__
__module____qualname____doc__r   r+   r    r  r    s     	r+   r  c                     t        | d      r| j                  S 	 t        |        |rt	        | |       S y# t        $ r Y yw xY w)aY  
    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  rE   r   r6   )r   r   s     r    r@   r@     sQ    ^ q+{{Q a)))	  s   5 	A Ac                 j    t        | d      xr t        |       xs t        |      xr t        | |      S )a  
    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

    rb  )r<   r@   r8  r6   )r   includes     r    r0   r0     s;    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                 "    ddl m}  || |      S )Nr   )postorder_traversal)r<  )sympy.core.traversalr  )r   r<  _postorder_traversals      r    r  r  3  s     Q4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                     ddl m}  ||       S )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                      ddl m}  || i |S )Nr   )default_sort_key)sympyr  )r8   kwargs_default_sort_keys      r    r  r  T  s     <d-f--r+   c                      ddl m}  || i |S )Nr   r  )r  r  )r8   r  _ordereds      r    r  r  a  s     *T$V$$r+   r   )NN)r   )T)NF)F)r3   Nr   r   r/   )NNF)NTrV  )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>   rI   rO   r[   rj   rl   ru   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r	  r  r   r(  r,  r6  r0  rC  rQ  r\  r/  r[  rj  rm  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   rs   r@   r0   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+   