
\c           @  sw   d  d l  m Z m Z d  d l m Z d e f d     YZ d   Z d   Z d   Z	 d f  d	     YZ
 d
   Z d S(   i(   t   print_functiont   division(   t   ranget   PartComponentc           B  s8   e  Z d  Z d Z d   Z d   Z d   Z d   Z RS(	   sX  Internal class used in support of the multiset partitions
    enumerators and the associated visitor functions.

    Represents one component of one part of the current partition.

    A stack of these, plus an auxiliary frame array, f, represents a
    partition of the multiset.

    Knuth's pseudocode makes c, u, and v separate arrays.
    t   ct   ut   vc         C  s   d |  _  d |  _ d |  _ d  S(   Ni    (   R   R   R   (   t   self(    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   __init__m   s    		c         C  s   d |  j  |  j |  j f S(   s&   for debug/algorithm animation purposess   c:%d u:%d v:%d(   R   R   R   (   R   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   __repr__w   s    c         C  sF   t  | |  j  oE |  j | j k oE |  j | j k oE |  j | j k S(   s<   Define  value oriented equality, which is useful for testers(   t
   isinstancet	   __class__R   R   R   (   R   t   other(    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   __eq__{   s    c         C  s   |  | k S(   s#   Defined for consistency with __eq__(    (   R   R   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   __ne__   s    (   R   R   R   (   t   __name__t
   __module__t   __doc__t	   __slots__R   R	   R   R   (    (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyR   _   s   
	
		c         c  s  t  |   } t |   } g  t | | d  D] } t   ^ q- } d g | d } xA t |  D]3 } | | } | | _ |  | | _ |  | | _ q` Wd | d <d } d }	 | | d <| }
 x2t rx?t r| } |
 } t } x | |
 k  r| | j | | j | | _ | | j d k r+t } n | s| | j | | _ t	 | | j | | j  | | _ | | j | | j k  } | d } n2 | | j | | _ | | j | | _ | d } | d } q W| |
 k r|
 } | }
 |	 d }	 |
 | |	 d <q Pq W| |	 | g } | Vx t r|
 d } x! | | j d k rR| d } q2W| | k r| | j d k r|	 d k rd S|	 d }	 | }
 | |	 } q| | j d | | _ x/ t | d |
  D] } | | j | | _ qWPqWq Wd S(   s  Enumerates partitions of a multiset.

    Parameters
    ==========

    multiplicities
         list of integer multiplicities of the components of the multiset.

    Yields
    ======

    state
        Internal data structure which encodes a particular partition.
        This output is then usually processed by a vistor function
        which combines the information from this data structure with
        the components themselves to produce an actual partition.

        Unless they wish to create their own visitor function, users will
        have little need to look inside this data structure.  But, for
        reference, it is a 3-element list with components:

        f
            is a frame array, which is used to divide pstack into parts.

        lpart
            points to the base of the topmost part.

        pstack
            is an array of PartComponent objects.

        The ``state`` output offers a peek into the internal data
        structures of the enumeration function.  The client should
        treat this as read-only; any modification of the data
        structure will cause unpredictable (and almost certainly
        incorrect) results.  Also, the components of ``state`` are
        modified in place at each iteration.  Hence, the visitor must
        be called at each loop iteration.  Accumulating the ``state``
        instances and processing them later will not work.

    Examples
    ========

    >>> from sympy.utilities.enumerative import list_visitor
    >>> from sympy.utilities.enumerative import multiset_partitions_taocp
    >>> # variables components and multiplicities represent the multiset 'abb'
    >>> components = 'ab'
    >>> multiplicities = [1, 2]
    >>> states = multiset_partitions_taocp(multiplicities)
    >>> list(list_visitor(state, components) for state in states)
    [[['a', 'b', 'b']],
    [['a', 'b'], ['b']],
    [['a'], ['b', 'b']],
    [['a'], ['b'], ['b']]]

    See Also
    ========

    sympy.utilities.iterables.multiset_partitions: Takes a multiset
        as input and directly yields multiset partitions.  It
        dispatches to a number of functions, including this one, for
        implementation.  Most users will find it more convenient to
        use than multiset_partitions_taocp.

    i   i    N(
   t   lent   sumR   R   R   R   R   t   Truet   Falset   min(   t   multiplicitiest   mt   nt   it   pstackt   ft   jt   pst   at   lpartt   bt   kt   xt   state(    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   multiset_partitions_taocp   sl    D	*
	

			$

	

c   	      C  s   |  \ } } } g  } xy t  | d  D]g } d } xK | | | | | d !D]0 } | j d k rL | | | j | j 9} qL qL W| j |  q& W| S(   s  Use with multiset_partitions_taocp to enumerate the ways a
    number can be expressed as a product of factors.  For this usage,
    the exponents of the prime factors of a number are arguments to
    the partition enumerator, while the corresponding prime factors
    are input here.

    Examples
    ========

    To enumerate the factorings of a number we can think of the elements of the
    partition as being the prime factors and the multiplicities as being their
    exponents.

    >>> from sympy.utilities.enumerative import factoring_visitor
    >>> from sympy.utilities.enumerative import multiset_partitions_taocp
    >>> from sympy import factorint
    >>> primes, multiplicities = zip(*factorint(24).items())
    >>> primes
    (2, 3)
    >>> multiplicities
    (3, 1)
    >>> states = multiset_partitions_taocp(multiplicities)
    >>> list(factoring_visitor(state, primes) for state in states)
    [[24], [8, 3], [12, 2], [4, 6], [4, 2, 3], [6, 2, 2], [2, 2, 2, 3]]
    i   i    (   R   R   R   t   append(	   R%   t   primesR   R!   R   t	   factoringR   t   factorR   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   factoring_visitor3  s     c   	      C  s   |  \ } } } g  } x t  | d  D]m } g  } xQ | | | | | d !D]6 } | j d k rL | j | | j g | j  qL qL W| j |  q& W| S(   s  Return a list of lists to represent the partition.

    Examples
    ========

    >>> from sympy.utilities.enumerative import list_visitor
    >>> from sympy.utilities.enumerative import multiset_partitions_taocp
    >>> states = multiset_partitions_taocp([1, 2, 1])
    >>> s = next(states)
    >>> list_visitor(s, 'abc')  # for multiset 'a b b c'
    [['a', 'b', 'b', 'c']]
    >>> s = next(states)
    >>> list_visitor(s, [1, 2, 3])  # for multiset '1 2 2 3
    [[1, 2, 2], [3]]
    i   i    (   R   R   t   extendR   R'   (	   R%   t
   componentsR   R!   R   t	   partitionR   t   partR   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   list_visitorX  s     %t   MultisetPartitionTraverserc           B  s   e  Z d  Z d   Z d   Z d   Z d   Z d   Z d   Z d   Z	 d   Z
 d	   Z d
   Z d   Z d   Z d   Z d   Z d   Z RS(   s)  
    Has methods to ``enumerate`` and ``count`` the partitions of a multiset.

    This implements a refactored and extended version of Knuth's algorithm
    7.1.2.5M [AOCP]_."

    The enumeration methods of this class are generators and return
    data structures which can be interpreted by the same visitor
    functions used for the output of ``multiset_partitions_taocp``.

    Examples
    ========

    >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
    >>> m = MultisetPartitionTraverser()
    >>> m.count_partitions([4,4,4,2])
    127750
    >>> m.count_partitions([3,3,3])
    686

    See Also
    ========

    multiset_partitions_taocp
    sympy.utilities.iterables.multiset_partititions

    References
    ==========

    .. [AOCP] Algorithm 7.1.2.5M in Volume 4A, Combinatoral Algorithms,
           Part 1, of The Art of Computer Programming, by Donald Knuth.

    .. [Factorisatio] On a Problem of Oppenheim concerning
           "Factorisatio Numerorum" E. R. Canfield, Paul Erdos, Carl
           Pomerance, JOURNAL OF NUMBER THEORY, Vol. 17, No. 1. August
           1983.  See section 7 for a description of an algorithm
           similar to Knuth's.

    .. [Yorgey] Generating Multiset Partitions, Brent Yorgey, The
           Monad.Reader, Issue 8, September 2007.

    c         C  s(   t  |  _ d |  _ d |  _ d |  _ d  S(   Ni    (   R   t   debugt   k1t   k2t   p1(   R   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyR     s    			c         C  sl   |  j  rh d } |  j |  j |  j g } t d | g  t | |  D] } d j |  ^ q@ t |   n  d S(   se   Useful for usderstanding/debugging the algorithms.  Not
        generally activated in end-user code.t   abcdefghijklmnopqrstuvwxyzs   DBG:t    N(   R2   R   R!   R   t   printR0   t   joint   animation_visitor(   R   t   msgt   lettersR%   R/   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   db_trace  s    		(c         C  s   t  |  } t |  } g  t | | d  D] } t   ^ q- |  _ d g | d |  _ xD t |  D]6 } |  j | } | | _ | | | _ | | | _ qf Wd |  j d <| |  j d <d |  _	 d S(   s   Allocates and initializes the partition stack.

        This is called from the enumeration/counting routines, so
        there is no need to call it separately.i   i    N(
   R   R   R   R   R   R   R   R   R   R!   (   R   R   t   num_componentst   cardinalityR   R   R   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   _initialize_enumeration  s    *	c         C  s   t  |  } x t | d d d  D] } | d k rH | | j d k sg | d k r# | | j d k r# | | j d 8_ x/ t | d |  D] } | | j | | _ q Wt Sq# Wt S(   s*  Decrements part (a subrange of pstack), if possible, returning
        True iff the part was successfully decremented.

        If you think of the v values in the part as a multi-digit
        integer (least significant digit on the right) this is
        basically decrementing that integer, but with the extra
        constraint that the leftmost digit cannot be decremented to 0.

        Parameters
        ==========

        part
           The part, represented as a list of PartComponent objects,
           which is to be decremented.

        i   ii    (   R   R   R   R   R   R   (   R   R/   t   plenR   R#   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   decrement_part  s    >c         C  s  |  j  | d k r& |  j d 7_ t St |  } x`t | d d d  D]H} | d k r | d j d | |  j  | d j k  r |  j d 7_ t S| d k r | | j d k s | d k rI | | j d k rI | | j d 8_ x/ t | d |  D] } | | j | | _ q W| d k r| d j d k r| d j | d j | |  j  d | d j k r|  j d 7_ |  j	 d  t St
 SqI Wt S(   s  Decrements part (a subrange of pstack), if possible, returning
        True iff the part was successfully decremented.

        Parameters
        ==========

        part
            part to be decremented (topmost part on the stack)

        ub
            the maximum number of parts allowed in a partition
            returned by the calling traversal.

        Notes
        =====

        The goal of this modification of the ordinary decrement method
        is to fail (meaning that the subtree rooted at this part is to
        be skipped) when it can be proved that this part can only have
        child partitions which are larger than allowed by ``ub``. If a
        decision is made to fail, it must be accurate, otherwise the
        enumeration will miss some partitions.  But, it is OK not to
        capture all the possible failures -- if a part is passed that
        shouldn't be, the resulting too-large partitions are filtered
        by the enumeration one level up.  However, as is usual in
        constrained enumerations, failing early is advantageous.

        The tests used by this method catch the most common cases,
        although this implementation is by no means the last word on
        this problem.  The tests include:

        1) ``lpart`` must be less than ``ub`` by at least 2.  This is because
           once a part has been decremented, the partition
           will gain at least one child in the spread step.

        2) If the leading component of the part is about to be
           decremented, check for how many parts will be added in
           order to use up the unallocated multiplicity in that
           leading component, and fail if this number is greater than
           allowed by ``ub``.  (See code for the exact expression.)  This
           test is given in the answer to Knuth's problem 7.2.1.5.69.

        3) If there is *exactly* enough room to expand the leading
           component by the above test, check the next component (if
           it exists) once decrementing has finished.  If this has
           ``v == 0``, this next component will push the expansion over the
           limit by 1, so fail.
        i   ii    s   Decrement fails test 3(   R!   R5   R   R   R   R   R   R3   R4   R=   R   (   R   R/   t   ubRA   R   R#   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   decrement_part_small  s(    15>c   	      C  sI  | d k r" |  j  |  s" t Sn  | |  j } | d k r? t St d   | D  } t d   | D  } | | k r{ t S| | | } | d k r t Sx t t |  d d d  D] } | d k r | d j | k r | d j | 8_ t St Sq | | j | k r#| | j | 8_ t S| | | j 8} d | | _ q Wd S(   s  Decrements part, while respecting size constraint.

        A part can have no children which are of sufficient size (as
        indicated by ``lb``) unless that part has sufficient
        unallocated multiplicity.  When enforcing the size constraint,
        this method will decrement the part (if necessary) by an
        amount needed to ensure sufficient unallocated multiplicity.

        Returns True iff the part was successfully decremented.

        Parameters
        ==========

        part
            part to be decremented (topmost part on the stack)

        amt
            Can only take values 0 or 1.  A value of 1 means that the
            part must be decremented, and then the size constraint is
            enforced.  A value of 0 means just to enforce the ``lb``
            size constraint.

        lb
            The partitions produced by the calling enumeration must
            have more parts than this value.

        i   i    c         s  s   |  ] } | j  Vq d  S(   N(   R   (   t   .0t   pc(    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pys	   <genexpr>o  s    c         s  s   |  ] } | j  Vq d  S(   N(   R   (   RE   RF   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pys	   <genexpr>p  s    iN(   RB   R   R!   R   R   R   R   R   (	   R   R/   t   amtt   lbt   min_unalloct
   total_multt   total_alloct   deficitR   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   decrement_part_largeD  s0    #c         C  s%   |  j  | |  o$ |  j | d |  S(   s  Decrements part (a subrange of pstack), if possible, returning
        True iff the part was successfully decremented.

        Parameters
        ==========

         part
            part to be decremented (topmost part on the stack)

        ub
            the maximum number of parts allowed in a partition
            returned by the calling traversal.

        lb
            The partitions produced by the calling enumeration must
            have more parts than this value.

        Notes
        =====

        Combines the constraints of _small and _large decrement
        methods.  If returns success, part has been decremented at
        least once, but perhaps by quite a bit more if needed to meet
        the lb constraint.
        i    (   RD   RM   (   R   R/   RH   RC   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   decrement_part_range  s    !c         C  s  |  j  |  j } |  j  |  j d } | } t } xt |  j  |  j |  j  |  j d  D] } |  j | j |  j | j |  j | _ |  j | j d k r t } qX |  j | j |  j | _ | r |  j | j |  j | _ n] |  j | j |  j | j k  r%|  j | j |  j | _ t } n |  j | j |  j | _ | d } qX W| | k r|  j d |  _ | |  j  |  j d <t St S(   s  Returns True if a new part has been created, and
        adjusts pstack, f and lpart as needed.

        Notes
        =====

        Spreads unallocated multiplicity from the current top part
        into a new part created above the current on the stack.  This
        new part is constrained to be less than or equal to the old in
        terms of the part ordering.

        This call does nothing (and returns False) if the current top
        part has no unallocated multiplicity.

        i   i    (	   R   R!   R   R   R   R   R   R   R   (   R   R   R#   t   baset   changed(    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   spread_part_multiplicity  s*    .(	 	c         C  s&   |  j  |  j |  j |  j |  j d !S(   sE   Return current top part on the stack, as a slice of pstack.

        i   (   R   R   R!   (   R   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   top_part  s    c         c  s   |  j  |  xx t r x |  j   r( q W|  j |  j |  j g } | Vx; |  j |  j    s |  j d k rq d S|  j d 8_ qI Wq Wd S(   s  Enumerate the partitions of a multiset.

        Examples
        ========

        >>> from sympy.utilities.enumerative import list_visitor
        >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
        >>> m = MultisetPartitionTraverser()
        >>> states = m.enum_all([2,2])
        >>> list(list_visitor(state, 'ab') for state in states)
        [[['a', 'a', 'b', 'b']],
        [['a', 'a', 'b'], ['b']],
        [['a', 'a'], ['b', 'b']],
        [['a', 'a'], ['b'], ['b']],
        [['a', 'b', 'b'], ['a']],
        [['a', 'b'], ['a', 'b']],
        [['a', 'b'], ['a'], ['b']],
        [['a'], ['a'], ['b', 'b']],
        [['a'], ['a'], ['b'], ['b']]]

        See Also
        ========

        multiset_partitions_taocp():
            which provides the same result as this method, but is
            about twice as fast.  Hence, enum_all is primarily useful
            for testing.  Also see the function for a discussion of
            states and visitors.

        i    Ni   (   R@   R   RQ   R   R!   R   RB   RR   (   R   R   R%   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   enum_all  s    	c         c  s-  d |  _  | d k r d S|  j |  x t r(t } x_ |  j   r |  j d  |  j | k r8 |  j  d 7_  t } |  j d  | d |  _ Pq8 q8 W| r |  j |  j |  j g } | Vn  xX |  j	 |  j
   |  s|  j d  |  j d k r d S|  j d 8_ |  j d  q W|  j d	  q) Wd S(
   s  Enumerate multiset partitions with no more than ``ub`` parts.

        Equivalent to enum_range(multiplicities, 0, ub)

        Parameters
        ==========

        multiplicities
             list of multiplicities of the components of the multiset.

        ub
            Maximum number of parts

        Examples
        ========

        >>> from sympy.utilities.enumerative import list_visitor
        >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
        >>> m = MultisetPartitionTraverser()
        >>> states = m.enum_small([2,2], 2)
        >>> list(list_visitor(state, 'ab') for state in states)
        [[['a', 'a', 'b', 'b']],
        [['a', 'a', 'b'], ['b']],
        [['a', 'a'], ['b', 'b']],
        [['a', 'b', 'b'], ['a']],
        [['a', 'b'], ['a', 'b']]]

        The implementation is based, in part, on the answer given to
        exercise 69, in Knuth [AOCP]_.

        See Also
        ========

        enum_all, enum_large, enum_range

        i    Ns   spread 1i   s     Discardingi   s$   Failed decrement, going to backtracks   Backtracked tos   decrement ok, about to expand(   t	   discardedR@   R   RQ   R=   R!   R   R   R   RD   RR   (   R   R   RC   t   good_partitionR%   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt
   enum_small  s0    (		c         c  s  d |  _  | t |  k r d S|  j |  |  j |  j   d |  x t rt } xD |  j   r |  j |  j   d |  sW |  j  d 7_  t } PqW qW W| r |  j |  j	 |  j
 g } | Vn  xA |  j |  j   d |  s|  j	 d k r d S|  j	 d 8_	 q WqH Wd S(   s  Enumerate the partitions of a multiset with lb < num(parts)

        Equivalent to enum_range(multiplicities, lb, sum(multiplicities))

        Parameters
        ==========

        multiplicities
            list of multiplicities of the components of the multiset.

        lb
            Number of parts in the partition must be greater than
            this lower bound.


        Examples
        ========

        >>> from sympy.utilities.enumerative import list_visitor
        >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
        >>> m = MultisetPartitionTraverser()
        >>> states = m.enum_large([2,2], 2)
        >>> list(list_visitor(state, 'ab') for state in states)
        [[['a', 'a'], ['b'], ['b']],
        [['a', 'b'], ['a'], ['b']],
        [['a'], ['a'], ['b', 'b']],
        [['a'], ['a'], ['b'], ['b']]]

        See Also
        ========

        enum_all, enum_small, enum_range

        i    Ni   (   RT   R   R@   RM   RR   R   RQ   R   R   R!   R   (   R   R   RH   RU   R%   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt
   enum_largeU  s&    #		c         c  s  d |  _  | d k s' | t |  k r+ d S|  j |  |  j |  j   d |  xDt rt } x |  j   r|  j d  |  j |  j   d |  s |  j d  |  j  d 7_  t } Pqc |  j	 | k rc |  j  d 7_  t } |  j d  | d |  _	 Pqc qc W| r)|  j
 |  j	 |  j g } | Vn  x[ |  j |  j   | |  s|  j d  |  j	 d k rgd S|  j	 d 8_	 |  j d	  q,W|  j d
  qT Wd S(   s  Enumerate the partitions of a multiset with
        ``lb < num(parts) <= ub``.

        In particular, if partitions with exactly ``k`` parts are
        desired, call with ``(multiplicities, k - 1, k)``.  This
        method generalizes enum_all, enum_small, and enum_large.

        Examples
        ========

        >>> from sympy.utilities.enumerative import list_visitor
        >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
        >>> m = MultisetPartitionTraverser()
        >>> states = m.enum_range([2,2], 1, 2)
        >>> list(list_visitor(state, 'ab') for state in states)
        [[['a', 'a', 'b'], ['b']],
        [['a', 'a'], ['b', 'b']],
        [['a', 'b', 'b'], ['a']],
        [['a', 'b'], ['a', 'b']]]

        i    Ns   spread 1s     Discarding (large cons)i   s     Discarding small consi   s$   Failed decrement, going to backtracks   Backtracked tos   decrement ok, about to expand(   RT   R   R@   RM   RR   R   RQ   R=   R   R!   R   R   RN   (   R   R   RH   RC   RU   R%   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt
   enum_range  s<    		c         C  s   d |  _  |  j |  xm t r x |  j   r1 q" W|  j  d 7_  x> |  j |  j    s |  j d k ro |  j  S|  j d 8_ qD Wq Wd S(   s  Returns the number of partitions of a multiset whose elements
        have the multiplicities given in ``multiplicities``.

        Primarily for comparison purposes.  It follows the same path as
        enumerate, and counts, rather than generates, the partitions.

        See Also
        ========

        count_partitions
            Has the same calling interface, but is much faster.

        i    i   N(   t   pcountR@   R   RQ   RB   RR   R!   (   R   R   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   count_partitions_slow  s    		c         C  s  d |  _  g  |  _ t |  d  s- i  |  _ n  |  j |  t |  j    } |  j j | d f g  x:t rxz |  j	   r t |  j    } | |  j k r |  j  |  j | d 7_  |  j
 d 8_
 Pqq |  j j | |  j  f g  qq W|  j  d 7_  xr |  j |  j    snx1 |  j j   D]  \ } } |  j  | |  j | <q"W|  j
 d k r\|  j  S|  j
 d 8_
 q Wt |  j    } |  j d j | |  j  f  qh Wd S(   s  Returns the number of partitions of a multiset whose components
        have the multiplicities given in ``multiplicities``.

        For larger counts, this method is much faster than calling one
        of the enumerators and counting the result.  Uses dynamic
        programming to cut down on the number of nodes actually
        explored.  The dictionary used in order to accelerate the
        counting process is stored in the ``MultisetPartitionTraverser``
        object and persists across calls.  If the user does not
        expect to call ``count_partitions`` for any additional
        multisets, the object should be cleared to save memory.  On
        the other hand, the cache built up from one count run can
        significantly speed up subsequent calls to ``count_partitions``,
        so it may be advantageous not to clear the object.

        Examples
        ========

        >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
        >>> m = MultisetPartitionTraverser()
        >>> m.count_partitions([9,8,2])
        288716
        >>> m.count_partitions([2,2])
        9
        >>> del m

        Notes
        =====

        If one looks at the workings of Knuth's algorithm M [AOCP]_, it
        can be viewed as a traversal of a binary tree of parts.  A
        part has (up to) two children, the left child resulting from
        the spread operation, and the right child from the decrement
        operation.  The ordinary enumeration of multiset partitions is
        an in-order traversal of this tree, and with the partitions
        corresponding to paths from the root to the leaves. The
        mapping from paths to partitions is a little complicated,
        since the partition would contain only those parts which are
        leaves or the parents of a spread link, not those which are
        parents of a decrement link.

        For counting purposes, it is sufficient to count leaves, and
        this can be done with a recursive in-order traversal.  The
        number of leaves of a subtree rooted at a particular part is a
        function only of that part itself, so memoizing has the
        potential to speed up the counting dramatically.

        This method follows a computational approach which is similar
        to the hypothetical memoized recursive function, but with two
        differences:

        1) This method is iterative, borrowing its structure from the
           other enumerations and maintaining an explicit stack of
           parts which are in the process of being counted.  (There
           may be multisets which can be counted reasonably quickly by
           this implementation, but which would overflow the default
           Python recursion limit with a recursive implementation.)

        2) Instead of using the part data structure directly, a more
           compact key is constructed.  This saves space, but more
           importantly coalesces some parts which would remain
           separate with physical keys.

        Unlike the enumeration functions, there is currently no _range
        version of count_partitions.  If someone wants to stretch
        their brain, it should be possible to construct one by
        memoizing with a histogram of counts rather than a single
        count, and combining the histograms.
        i    t   dp_mapi   iN(   RY   t   dp_stackt   hasattrR[   R@   t   part_keyRR   R'   R   RQ   R!   RB   t   pop(   R   R   t   pkeyt   keyt   oldcount(    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   count_partitions  s0    G		
	 (   R   R   R   R   R=   R@   RB   RD   RM   RN   RQ   RR   RS   RV   RW   RX   RZ   Rc   (    (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyR1   u  s    *						P	C	$	-		/	F	=	>	c         C  sA   g  } x. |  D]& } | j  | j  | j  | j  q Wt |  S(   s  Helper for MultisetPartitionTraverser.count_partitions that
    creates a key for ``part``, that only includes information which can
    affect the count for that part.  (Any irrelevant information just
    reduces the effectiveness of dynamic programming.)

    Notes
    =====

    This member function is a candidate for future exploration. There
    are likely symmetries that can be exploited to coalesce some
    ``part_key`` values, and thereby save space and improve
    performance.

    (   R'   R   R   t   tuple(   R/   t   rvalR   (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyR^   l  s
    N(   t
   __future__R    R   t   sympy.core.compatibilityR   t   objectR   R&   R+   R0   R1   R^   (    (    (    s:   lib/python2.7/site-packages/sympy/utilities/enumerative.pyt   <module>   s   ]6		%	  