
    wgh#                       d Z ddlmZmZ ddlmZ ddlmZ ddl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mZmZmZmZ dd
lmZ ddlmZmZ ddl m!Z! ddl"m#Z#m$Z$m%Z% ddl&m'Z'm(Z( ddl)m*Z* ddl+m,Z,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2m3Z3 ddl4m5Z5 ddl6m7Z8 ddl9m:Z: ddl;m<Z<m=Z=m>Z> ddl?m@Z@ ddlAmBZB ddlCmDZE ddlFmGZG ddlHmIZI ddlJmKZKmLZLmMZM ddlNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZY ddlZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z` ddlambZb dd lcmdZd dd!lemfZfmgZgmhZh dd"limjZj dd#lkmlZlmmZm dd$l6Zndd$loZodd%lpmqZq d& Zreg G d' d(e             Zseg G d) d*es             Ztegd+        Zud, Zvegd-        Zwd. Zxd/ Zyegdvd0       Zzegd1        Z{egd2        Z|egd3        Z}egd4        Z~egd5        Zegd6        Zegd7        Zegd8        Zegd9        Zegd:        Zegd;        Zegd<        Zegd=        Zegd>        Zegd?        Zegd@        ZegdA        ZegdBdCdD       ZegdE        ZegdF        ZegdG        ZegdwdH       ZegdI        ZegdwdJ       ZegdK        ZegdL        ZegdM        ZegdN        ZegdO        ZegdP        ZegdQ        ZegdR        ZegdS        ZegdT        ZegdU        ZegdV        ZdW ZdX ZdY ZdZ Zd[ Zd\ Zd] Zd^ Zegd_        Zegd`        Zegda        ZegdBdbdc       Zegdxdd       Zegdyde       Zegdzdf       Zegd{dh       Zegd{di       Zegd|dj       Zegdk        Zegdl        Zegdgdmdn       Zegdo        Zegdp        ZDegdq        Zeg G dr dse             Zegdt        Zdu Zy$)}z8User-friendly public interface to polynomial functions.     )wrapsreducemul)Optional)SExprAddTuple)Basic)
_sympifyit)Factors	factor_ncfactor_terms)pure_complexevalffastlog_evalf_with_bounded_errorquad_to_mpmath)
Derivative)Mul_keep_coeff)ilcm)IIntegerequal_valued)
RelationalEquality)ordered)DummySymbol)sympify_sympify)preorder_traversal	bottom_up)BooleanAtom)polyoptions)construct_domain)FFQQZZ)DomainElement)matrix_fglm)groebner)Monomial)monomial_key)DMPDMFANP)OperationNotSupportedDomainErrorCoercionFailedUnificationFailedGeneratorsNeededPolynomialErrorMultivariatePolynomialErrorExactQuotientFailedPolificationFailedComputationFailedGeneratorsError)basic_from_dict
_sort_gens_unify_gens_dict_reorder_dict_from_expr_parallel_dict_from_expr)together)dup_isolate_real_roots_list)grouppublic
filldedent)sympy_deprecation_warning)iterablesiftN)NoConvergencec                 .     t                fd       }|S )Nc                    t        |      }t        |t              r	 | |      S t        |t              r3 | j                  |g| j
                  d| j                  i} | |      S t        |t              r'	  | j                  |g| j
                   } | |      S t        S # t        $ r[ |j                  rt        cY S t        | j                         j                        } ||      }|t        urt        ddd       |cY S w xY w)Ndomaina@  
                        Mixing Poly with non-polynomial expressions in binary
                        operations is deprecated. Either explicitly convert
                        the non-Poly operand to a Poly with as_poly() or
                        convert the Poly to an Expr with as_expr().
                        z1.6z)deprecated-poly-nonpoly-binary-operations)deprecated_since_versionactive_deprecations_target)r#   
isinstancePolyr   	from_exprgensrP   r	   r9   	is_MatrixNotImplementedgetattras_expr__name__rJ   )fgexpr_methodresultfuncs       Z/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/polys/polytools.pywrapperz_polifyit.<locals>.wrapperE   s    QKa1:7#A88qxx8A1:4 "AKK+AFF+& Aqz!!!) # ;;))%aiik4==A$Q/- 273^	 !s   :B& &D
AD
	D
)r   )r`   rb   s   ` ra   	_polifyitrc   D   s     
4[" "> N    c                       e Zd ZdZdZdZdZdZd Ze	d        Z
ed        Zed        Zd	 Ze	d
        Ze	d        Ze	d        Ze	d        Ze	d        Ze	d        Ze	d        Ze	d        Ze	d        Z fdZed        Zed        Zed        Zed        Zed        Zed        Zed        Zd Z d Z!ddZ"d Z#d Z$d  Z%d! Z&d" Z'd# Z(dd$Z)d% Z*d& Z+d' Z,d( Z-d) Z.d* Z/d+ Z0dd,Z1dd-Z2dd.Z3dd/Z4dd0Z5d1 Z6d2 Z7d3 Z8d4 Z9d5 Z:dd6Z;dd7Z<d8 Z=d9 Z>d: Z?d; Z@dd<ZAd= ZBd> ZCd? ZDd@ ZEdA ZFdB ZGdC ZHdD ZIdE ZJdF ZKdG ZLdH ZMdI ZNdJ ZOdK ZPdL ZQdM ZRdN ZSddOZTddPZUddQZVddRZWdS ZXddTZYdU ZZdV Z[dW Z\dX Z]ddYZ^dZ Z_dd[Z`d\ Zad] Zbdd^Zcdd_Zddd`ZeddaZfddbZgdc Zhdd ZiddeZjdf Zkdg Zldh ZmemZnddiZodj ZpddkZqddlZrddmZsdn Ztdo ZuddpZvdq ZwddrZxddsZydt Zzdu Z{dv Z|dw Z}ddxZ~dy Zdz Zd{ Zd| Zd} Zd~ Zd ZddZd Zd Zd Zd ZddZddZd Zd ZddZddZddZddZddZddZddZd Zd Zd ZddZd ZddZed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zd Zd Zed        Zed        Zed        Zed        Zed        Zed        Z ede      d        Zed        Zed        Zed        Zed        Zed        Zed        Z ede      d        Z ede      d        Z ede      d        Z ede      d        Zd ZddZddZd ZÈ xZS )rT   aP  
    Generic class for representing and operating on polynomial expressions.

    See :ref:`polys-docs` for general documentation.

    Poly is a subclass of Basic rather than Expr but instances can be
    converted to Expr with the :py:meth:`~.Poly.as_expr` method.

    .. deprecated:: 1.6

       Combining Poly with non-Poly objects in binary operations is
       deprecated. Explicitly convert both objects to either Poly or Expr
       first. See :ref:`deprecated-poly-nonpoly-binary-operations`.

    Examples
    ========

    >>> from sympy import Poly
    >>> from sympy.abc import x, y

    Create a univariate polynomial:

    >>> Poly(x*(x**2 + x - 1)**2)
    Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ')

    Create a univariate polynomial with specific domain:

    >>> from sympy import sqrt
    >>> Poly(x**2 + 2*x + sqrt(3), domain='R')
    Poly(1.0*x**2 + 2.0*x + 1.73205080756888, x, domain='RR')

    Create a multivariate polynomial:

    >>> Poly(y*x**2 + x*y + 1)
    Poly(x**2*y + x*y + 1, x, y, domain='ZZ')

    Create a univariate polynomial, where y is a constant:

    >>> Poly(y*x**2 + x*y + 1,x)
    Poly(y*x**2 + y*x + 1, x, domain='ZZ[y]')

    You can evaluate the above polynomial as a function of y:

    >>> Poly(y*x**2 + x*y + 1,x).eval(2)
    6*y + 1

    See Also
    ========

    sympy.core.expr.Expr

    reprV   Tgn $@c                    t        j                  ||      }d|v rt        d      t        |t        t
        t        t        f      r| j                  ||      S t        |t              r=t        |t              r| j                  ||      S | j                  t        |      |      S t        |t!        |      t        u      }|j"                  r| j%                  ||      S | j'                  ||      S )z:Create a new polynomial instance out of something useful. orderz&'order' keyword is not implemented yet)exclude)evaluate)optionsbuild_optionsNotImplementedErrorrS   r1   r2   r3   r,   _from_domain_elementrK   strdict
_from_dict
_from_listlistr"   typeis_Poly
_from_poly
_from_exprclsrg   rV   argsopts        ra   __new__zPoly.__new__   s    ##D$/c>%&NOOcCc=9:++C55c3'#t$~~c3//~~d3i55#S	(<=C{{~~c3//~~c3//rd   c                     t        |t              st        d|z        |j                  t	        |      dz
  k7  rt        d|d|      t        j                  |       }||_        ||_        |S )z:Construct :class:`Poly` instance from raw representation. z%invalid polynomial representation: %s   zinvalid arguments: z, )	rS   r1   r9   levlenr   r}   rg   rV   )rz   rg   rV   objs       ra   newzPoly.new   sh     #s#!7#=? ?WWD	A%!d"KLLmmC 
rd   c                 ^    t        | j                  j                         g| j                   S N)r?   rg   to_sympy_dictrV   selfs    ra   exprz	Poly.expr   s#    txx557D$))DDrd   c                 6    | j                   f| j                  z   S r   )r   rV   r   s    ra   r{   z	Poly.args   s    		|dii''rd   c                 6    | j                   f| j                  z   S r   rf   r   s    ra   _hashable_contentzPoly._hashable_content   s    {TYY&&rd   c                 R    t        j                  ||      }| j                  ||      S )(Construct a polynomial from a ``dict``. )rl   rm   rr   ry   s        ra   	from_dictzPoly.from_dict   '     ##D$/~~c3''rd   c                 R    t        j                  ||      }| j                  ||      S )(Construct a polynomial from a ``list``. )rl   rm   rs   ry   s        ra   	from_listzPoly.from_list   r   rd   c                 R    t        j                  ||      }| j                  ||      S )*Construct a polynomial from a polynomial. )rl   rm   rw   ry   s        ra   	from_polyzPoly.from_poly   r   rd   c                 R    t        j                  ||      }| j                  ||      S +Construct a polynomial from an expression. )rl   rm   rx   ry   s        ra   rU   zPoly.from_expr   r   rd   c                 6   |j                   }|st        d      t        |      dz
  }|j                  }|t	        ||      \  }}n,|j                         D ]  \  }}|j                  |      ||<     | j                  t        j                  |||      g| S )r   z0Cannot initialize from 'dict' without generatorsr   r|   )
rV   r8   r   rP   r(   itemsconvertr   r1   r   )rz   rg   r|   rV   levelrP   monomcoeffs           ra   rr   zPoly._from_dict   s     xx"BD D D	A>*3C8KFC #		 3u#^^E2E
3 swws}}S%8@4@@rd   c                 N   |j                   }|st        d      t        |      dk7  rt        d      t        |      dz
  }|j                  }|t        ||      \  }}nt        t        |j                  |            } | j                  t        j                  |||      g| S )r   z0Cannot initialize from 'list' without generatorsr   z#'list' representation not supportedr   )rV   r8   r   r:   rP   r(   rt   mapr   r   r1   r   )rz   rg   r|   rV   r   rP   s         ra   rs   zPoly._from_list  s     xx"BD DY!^-57 7 D	A>*3C8KFCs6>>3/0Cswws}}S%8@4@@rd   c                    | |j                   k7  r' | j                  |j                  g|j                   }|j                  }|j                  }|j
                  }|r_|j                  |k7  rPt        |j                        t        |      k7  r | j                  |j                         |      S  |j                  | }d|v r|r|j                  |      }|S |du r|j                         }|S )r   rP   T)	__class__r   rg   rV   fieldrP   setrx   rZ   reorder
set_domainto_field)rz   rg   r|   rV   r   rP   s         ra   rw   zPoly._from_poly!  s     #--#''#''-CHH-Cxx		CHH$388}D	)~~ckkmS99!ckk4(s?v..(C 
 d],,.C
rd   c                 D    t        ||      \  }}| j                  ||      S r   )rC   rr   )rz   rg   r|   s      ra   rx   zPoly._from_expr8  s%     #3,S~~c3''rd   c                     |j                   }|j                  }t        |      dz
  }|j                  |      g} | j                  t        j                  |||      g| S Nr   )rV   rP   r   r   r   r1   r   )rz   rg   r|   rV   rP   r   s         ra   ro   zPoly._from_domain_element>  sU    xxD	A~~c"#swws}}S%8@4@@rd   c                      t         |          S r   super__hash__r   r   s    ra   r   zPoly.__hash__H      w!!rd   c                     t               }| j                  }t        t        |            D ]0  }| j	                         D ]  }||   s	|||   j
                  z  } 0 2 || j                  z  S )a  
        Free symbols of a polynomial expression.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y, z

        >>> Poly(x**2 + 1).free_symbols
        {x}
        >>> Poly(x**2 + y).free_symbols
        {x, y}
        >>> Poly(x**2 + y, x).free_symbols
        {x, y}
        >>> Poly(x**2 + y, x, z).free_symbols
        {x, y}

        )r   rV   ranger   monomsfree_symbolsfree_symbols_in_domain)r   symbolsrV   ir   s        ra   r   zPoly.free_symbolsK  sr    * %yys4y! 	A 8tAw333G	 4444rd   c                    | j                   j                  t               }}|j                  r"|j                  D ]  }||j
                  z  } |S |j                  r$| j                         D ]  }||j
                  z  } |S )aj  
        Free symbols of the domain of ``self``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x**2 + 1).free_symbols_in_domain
        set()
        >>> Poly(x**2 + y).free_symbols_in_domain
        set()
        >>> Poly(x**2 + y, x).free_symbols_in_domain
        {y}

        )rg   domr   is_Compositer   r   is_EXcoeffs)r   rP   r   genr   s        ra   r   zPoly.free_symbols_in_domainj  s    & ((,,~~ ,3+++, 	 \\ .5---. rd   c                      | j                   d   S )z
        Return the principal generator.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 + 1, x).gen
        x

        r   rV   r   s    ra   r   zPoly.gen  s     yy|rd   c                 "    | j                         S )a  Get the ground domain of a :py:class:`~.Poly`

        Returns
        =======

        :py:class:`~.Domain`:
            Ground domain of the :py:class:`~.Poly`.

        Examples
        ========

        >>> from sympy import Poly, Symbol
        >>> x = Symbol('x')
        >>> p = Poly(x**2 + x)
        >>> p
        Poly(x**2 + x, x, domain='ZZ')
        >>> p.domain
        ZZ
        )
get_domainr   s    ra   rP   zPoly.domain  s    *   rd   c                      | j                   | j                  j                  | j                  j                  | j                  j                        g| j
                   S )z3Return zero polynomial with ``self``'s properties. )r   rg   zeror   r   rV   r   s    ra   r   z	Poly.zero  =     txxdhhllDHHLLANDIINNrd   c                      | j                   | j                  j                  | j                  j                  | j                  j                        g| j
                   S )z2Return one polynomial with ``self``'s properties. )r   rg   oner   r   rV   r   s    ra   r   zPoly.one  s=     txxTXX\\488<<@M499MMrd   c                      | j                   | j                  j                  | j                  j                  | j                  j                        g| j
                   S )z3Return unit polynomial with ``self``'s properties. )r   rg   unitr   r   rV   r   s    ra   r   z	Poly.unit  r   rd   c                 N    | j                  |      \  }}}} ||       ||      fS )a  
        Make ``f`` and ``g`` belong to the same domain.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> f, g = Poly(x/2 + 1), Poly(2*x + 1)

        >>> f
        Poly(1/2*x + 1, x, domain='QQ')
        >>> g
        Poly(2*x + 1, x, domain='ZZ')

        >>> F, G = f.unify(g)

        >>> F
        Poly(1/2*x + 1, x, domain='QQ')
        >>> G
        Poly(2*x + 1, x, domain='QQ')

        )_unify)r\   r]   _perFGs         ra   unifyz
Poly.unify  s+    2 xx{311vs1v~rd   c           
      b   t        |      }|j                  sm	 | j                  j                  j	                  |      }| j                  j                  | j
                  | j                  | j                  j                  |      fS t        | j                  t              r<t        |j                  t              r!t        | j                  |j                        }| j                  j                  j                  |j                  j                  |      t        |      dz
  }}| j                  |k7  rt        | j                  j!                         | j                  |      \  }}| j                  j                  |k7  r3|D cg c](  }|j#                  || j                  j                        * }}t        j$                  t'        t)        t+        ||                  ||      }	n| j                  j#                  |      }	|j                  |k7  rt        |j                  j!                         |j                  |      \  }
}|j                  j                  |k7  r3|D cg c](  }|j#                  ||j                  j                        * }}t        j$                  t'        t)        t+        |
|                  ||      }n-|j                  j#                  |      }nt        d| d|      | j,                  ||d ffd	}|||	|fS # t        $ r t        d| d|      w xY wc c}w c c}w )NCannot unify  with r   c                 p    |!|d | ||dz   d  z   }|s|j                  |       S  j                  | g| S r   to_sympyr   rg   r   rV   removerz   s       ra   r   zPoly._unify.<locals>.per  L    !GV}tFQJK'88<<,,3773&&&rd   )r"   rv   rg   r   
from_sympyr   
ground_newr6   r7   rS   r1   rA   rV   r   r   rB   to_dictr   r   rq   rt   zipr   )r\   r]   g_coeffrV   r   r   f_monomsf_coeffscr   g_monomsg_coeffsr   r   rz   s                 @ra   r   zPoly._unify  sX   AJyyJ%%))..q1 uuyy!%%0@0@0IIIaeeS!j&<qvvqvv.Duuyyquuyy$7TQCvv~%2EEMMOQVVT&3"( 5599#CKLaAquuyy 9LHLMM$tC(,C'D"EsCPEEMM#&vv~%2EEMMOQVVT&3"( 5599#CKLaAquuyy 9LHLMM$tC(,C'D"EsCPEEMM#&#A$FGGkk4 	' CA~[ " L'Q(JKKL  M  Ms   %L	 -L'-L,	L$c                     || j                   }|5|d| ||dz   d z   }|s%| j                  j                  j                  |      S  | j                  j
                  |g| S )ab  
        Create a Poly out of the given representation.

        Examples
        ========

        >>> from sympy import Poly, ZZ
        >>> from sympy.abc import x, y

        >>> from sympy.polys.polyclasses import DMP

        >>> a = Poly(x**2 + 1)

        >>> a.per(DMP([ZZ(1), ZZ(1)], ZZ), gens=[y])
        Poly(y + 1, y, domain='ZZ')

        Nr   )rV   rg   r   r   r   r   )r\   rg   rV   r   s       ra   r   zPoly.per  si    $ <66D=4
#44Duuyy))#..q{{s*T**rd   c                     t        j                  | j                  d|i      }| j                  | j                  j                  |j                              S )z Set the ground domain of ``f``. rP   )rl   rm   rV   r   rg   r   rP   )r\   rP   r|   s      ra   r   zPoly.set_domain-  s=    ##AFFXv,>?uuQUU]]3::.//rd   c                 .    | j                   j                  S )z Get the ground domain of ``f``. )rg   r   r\   s    ra   r   zPoly.get_domain2  s    uuyyrd   c                 t    t         j                  j                  |      }| j                  t	        |            S )z
        Set the modulus of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(5*x**2 + 2*x - 1, x).set_modulus(2)
        Poly(x**2 + 1, x, modulus=2)

        )rl   Modulus
preprocessr   r)   )r\   moduluss     ra   set_moduluszPoly.set_modulus6  s+     //,,W5||BwK((rd   c                     | j                         }|j                  rt        |j                               S t	        d      )z
        Get the modulus of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 + 1, modulus=2).get_modulus()
        2

        z$not a polynomial over a Galois field)r   is_FiniteFieldr   characteristicr9   )r\   rP   s     ra   get_moduluszPoly.get_modulusG  s8       600233!"HIIrd   c                     || j                   v r1|j                  r| j                  ||      S 	 | j                  ||      S | j                         j                  ||      S # t        $ r Y +w xY w)z)Internal implementation of :func:`subs`. )rV   	is_numberevalreplacer9   rZ   subs)r\   oldr   s      ra   
_eval_subszPoly._eval_subs\  sj    !&&=}}vvc3''99S#.. yy{S)) ' s   A   	A,+A,c                     | j                   j                         \  }}t        | j                        D cg c]  \  }}||vs| }}}| j	                  ||      S c c}}w )a  
        Remove unnecessary generators from ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import a, b, c, d, x

        >>> Poly(a + x, a, b, c, d, x).exclude()
        Poly(a + x, a, x, domain='ZZ')

        r   )rg   rj   	enumeraterV   r   )r\   Jr   jr   rV   s         ra   rj   zPoly.excludei  sV     3"+AFF"3B3qzBBuuStu$$ Cs   AAc                    |&| j                   r| j                  |}}nt        d      ||k(  s|| j                  vr| S || j                  v r~|| j                  vrp| j	                         }|j
                  r||j                  vrFt        | j                        }|||j                  |      <   | j                  | j                  |      S t        d|d|d|       )a  
        Replace ``x`` with ``y`` in generators list.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x**2 + 1, x).replace(x, y)
        Poly(y**2 + 1, y, domain='ZZ')

        z(syntax supported only in univariate caser   zCannot replace r    in )is_univariater   r9   rV   r   r   r   rt   indexr   rg   )r\   xy_ignorer   rV   s         ra   r   zPoly.replace|  s     9uua1%>@ @ 6Qaff_H;1AFF?,,.C##q';AFF|&'TZZ]#uuQUUu..1aKLLrd   c                 B     | j                         j                  |i |S )z-Match expression from Poly. See Basic.match())rZ   match)r\   r{   kwargss      ra   r  z
Poly.match  s      qyy{  $1&11rd   c                    t        j                  d|      }|st        | j                  |      }n,t	        | j                        t	        |      k7  rt        d      t        t        t        t        | j                  j                         | j                  |                   }| j                  t        j                  |t        |      dz
  | j                  j                         |      S )a  
        Efficiently apply new order of generators.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x**2 + x*y**2, x, y).reorder(y, x)
        Poly(y**2*x + x**2, y, x, domain='ZZ')

         r   z7generators list can differ only up to order of elementsr   r   )rl   Optionsr@   rV   r   r9   rq   rt   r   rB   rg   r   r   r1   r   r   r   )r\   rV   r{   r|   rg   s        ra   r   zPoly.reorder  s     oob$'aff#.D[CI%!IK K 4]155==?AFFDIJKLuuS]]3D	AquuyyAuMMrd   c                 r   | j                  d      }| j                  |      }i }|j                         D ])  \  }}t        |d|       rt	        d| z        ||||d <   + | j
                  |d } | j                  t        j                  |t        |      dz
  | j                  j                        g| S )a(  
        Remove dummy generators from ``f`` that are to the left of
        specified ``gen`` in the generators as ordered. When ``gen``
        is an integer, it refers to the generator located at that
        position within the tuple of generators of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y, z

        >>> Poly(y**2 + y*z**2, x, y, z).ltrim(y)
        Poly(y**2 + y*z**2, y, z, domain='ZZ')
        >>> Poly(z, x, y, z).ltrim(-1)
        Poly(z, z, domain='ZZ')

        T)nativeNzCannot left trim %sr   )as_dict_gen_to_levelr   anyr9   rV   r   r1   r   r   rg   r   )r\   r   rg   r   termsr   r   rV   s           ra   ltrimz
Poly.ltrim  s    & iiti$OOC IIK 	%LE55!9~%&;a&?@@$E%)	% vvabzquuS]]5#d)a-CKdKKrd   c                     t               }|D ]/  }	 | j                  j                  |      }|j                  |       1 | j                         D ]  }t        |      D ]  \  }}||vs|s  y ! y# t        $ r t        | d|d      w xY w)aJ  
        Return ``True`` if ``Poly(f, *gens)`` retains ground domain.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y, z

        >>> Poly(x*y + 1, x, y, z).has_only_gens(x, y)
        True
        >>> Poly(x*y + z, x, y, z).has_only_gens(x, y)
        False

         doesn't have  as generatorFT)r   rV   r   add
ValueErrorr>   r   r   )r\   rV   indicesr   r   r   r   elts           ra   has_only_genszPoly.has_only_gens  s      % 	#C#S)
 E"	# XXZ 	!E#E* !3G# !	!
   B%9:C@B BBs   A22Bc                     t        | j                  d      r| j                  j                         }nt        | d      | j	                  |      S )z
        Make the ground domain a ring.

        Examples
        ========

        >>> from sympy import Poly, QQ
        >>> from sympy.abc import x

        >>> Poly(x**2 + 1, domain=QQ).to_ring()
        Poly(x**2 + 1, x, domain='ZZ')

        to_ring)hasattrrg   r  r4   r   r\   r_   s     ra   r  zPoly.to_ring  s<     155)$UU]]_F'955uuV}rd   c                     t        | j                  d      r| j                  j                         }nt        | d      | j	                  |      S )z
        Make the ground domain a field.

        Examples
        ========

        >>> from sympy import Poly, ZZ
        >>> from sympy.abc import x

        >>> Poly(x**2 + 1, x, domain=ZZ).to_field()
        Poly(x**2 + 1, x, domain='QQ')

        r   )r  rg   r   r4   r   r  s     ra   r   zPoly.to_field  =     155*%UU^^%F':66uuV}rd   c                     t        | j                  d      r| j                  j                         }nt        | d      | j	                  |      S )z
        Make the ground domain exact.

        Examples
        ========

        >>> from sympy import Poly, RR
        >>> from sympy.abc import x

        >>> Poly(x**2 + 1.0, x, domain=RR).to_exact()
        Poly(x**2 + 1, x, domain='QQ')

        to_exact)r  rg   r   r4   r   r  s     ra   r   zPoly.to_exact-  r  rd   c                     t        | j                  d      || j                  j                  xs d      \  }}| j	                  || j
                  |      S )a  
        Recalculate the ground domain of a polynomial.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> f = Poly(x**2 + 1, x, domain='QQ[y]')
        >>> f
        Poly(x**2 + 1, x, domain='QQ[y]')

        >>> f.retract()
        Poly(x**2 + 1, x, domain='ZZ')
        >>> f.retract(field=True)
        Poly(x**2 + 1, x, domain='QQ')

        Tr   N)r   	compositerP   )r(   r  rP   r   r   rV   )r\   r   r   rg   s       ra   retractzPoly.retractB  sM    ( $AII4I$8188#8#8#@DBS{{3s{33rd   c                    |d||}}}n| j                  |      }t        |      t        |      }}t        | j                  d      r| j                  j	                  |||      }nt        | d      | j                  |      S )z1Take a continuous subsequence of terms of ``f``. r   slice)r  intr  rg   r'  r4   r   )r\   r  mnr   r_   s         ra   r'  z
Poly.sliceZ  sr    9A!qA"A1vs1v1155'"UU[[Aq)F'733uuV}rd   c                     | j                   j                  |      D cg c]'  }| j                   j                  j                  |      ) c}S c c}w )aQ  
        Returns all non-zero coefficients from ``f`` in lex order.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**3 + 2*x + 3, x).coeffs()
        [1, 2, 3]

        See Also
        ========
        all_coeffs
        coeff_monomial
        nth

        ri   )rg   r   r   r   )r\   ri   r   s      ra   r   zPoly.coeffsj  s:    ( 01uu||%|/HI!		""1%IIIs   ,Ac                 :    | j                   j                  |      S )aU  
        Returns all non-zero monomials from ``f`` in lex order.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).monoms()
        [(2, 0), (1, 2), (1, 1), (0, 1)]

        See Also
        ========
        all_monoms

        r,  )rg   r   r\   ri   s     ra   r   zPoly.monoms  s    $ uu||%|((rd   c                     | j                   j                  |      D cg c],  \  }}|| j                   j                  j                  |      f. c}}S c c}}w )ac  
        Returns all non-zero terms from ``f`` in lex order.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).terms()
        [((2, 0), 1), ((1, 2), 2), ((1, 1), 1), ((0, 1), 3)]

        See Also
        ========
        all_terms

        r,  )rg   r  r   r   )r\   ri   r)  r   s       ra   r  z
Poly.terms  sC    $ 89uu{{{7OPtq!AEEII&&q)*PPPs   1Ac                     | j                   j                         D cg c]'  }| j                   j                  j                  |      ) c}S c c}w )a  
        Returns all coefficients from a univariate polynomial ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**3 + 2*x - 1, x).all_coeffs()
        [1, 0, 2, -1]

        )rg   
all_coeffsr   r   )r\   r   s     ra   r1  zPoly.all_coeffs  s8     01uu/?/?/AB!		""1%BBBs   ,Ac                 6    | j                   j                         S )a?  
        Returns all monomials from a univariate polynomial ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**3 + 2*x - 1, x).all_monoms()
        [(3,), (2,), (1,), (0,)]

        See Also
        ========
        all_terms

        )rg   
all_monomsr   s    ra   r3  zPoly.all_monoms  s    $ uu!!rd   c                     | j                   j                         D cg c],  \  }}|| j                   j                  j                  |      f. c}}S c c}}w )a  
        Returns all terms from a univariate polynomial ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**3 + 2*x - 1, x).all_terms()
        [((3,), 1), ((2,), 0), ((1,), 2), ((0,), -1)]

        )rg   	all_termsr   r   )r\   r)  r   s      ra   r5  zPoly.all_terms  s?     89uu7HItq!AEEII&&q)*IIIs   1Ac                     i }| j                         D ]@  \  }} |||      }t        |t              r|\  }}n|}|s*||vr|||<   4t        d|z          | j                  |g|xs | j
                  i |S )ah  
        Apply a function to all terms of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> def func(k, coeff):
        ...     k = k[0]
        ...     return coeff//10**(2-k)

        >>> Poly(x**2 + 20*x + 400).termwise(func)
        Poly(x**2 + 2*x + 4, x, domain='ZZ')

        z%s monomial was generated twice)r  rS   tupler9   r   rV   )r\   r`   rV   r{   r  r   r   r_   s           ra   termwisezPoly.termwise  s    $ GGI 	CLE5%'F&%(%u%#(E%L)9EAC C	C q{{5<DNAFF<t<<rd   c                 4    t        | j                               S )z
        Returns the number of non-zero terms in ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 + 2*x - 1).length()
        3

        )r   r  r   s    ra   lengthzPoly.length  s     199;rd   c                 v    |r| j                   j                  |      S | j                   j                  |      S )a  
        Switch to a ``dict`` representation.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x**2 + 2*x*y**2 - y, x, y).as_dict()
        {(0, 1): -1, (1, 2): 2, (2, 0): 1}

        r"  )rg   r   r   )r\   r  r   s      ra   r  zPoly.as_dict  s4     55==d=++55&&D&11rd   c                 n    |r| j                   j                         S | j                   j                         S )z%Switch to a ``list`` representation. )rg   to_listto_sympy_list)r\   r  s     ra   as_listzPoly.as_list$  s(    55==?"55&&((rd   c                 v   |s| j                   S t        |      dk(  r\t        |d   t              rI|d   }t	        | j
                        }|j                         D ]  \  }}	 |j                  |      }|||<    t        | j                  j                         g| S # t        $ r t        | d|d      w xY w)ar  
        Convert a Poly instance to an Expr instance.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> f = Poly(x**2 + 2*x*y**2 - y, x, y)

        >>> f.as_expr()
        x**2 + 2*x*y**2 - y
        >>> f.as_expr({x: 5})
        10*y**2 - y + 25
        >>> f.as_expr(5, 6)
        379

        r   r   r  r  )r   r   rS   rq   rt   rV   r   r   r  r>   r?   rg   r   )r\   rV   mappingr   valuer   s         ra   rZ   zPoly.as_expr+  s    ( 66Mt9>ja$71gG<D%mmo (
U( JJsOE
 #(DK( quu224<t<< " F)=>DF FFs   !BB8c                 ^    	 t        | g|i |}|j                  sy|S # t        $ r Y yw xY w)a{  Converts ``self`` to a polynomial or returns ``None``.

        >>> from sympy import sin
        >>> from sympy.abc import x, y

        >>> print((x**2 + x*y).as_poly())
        Poly(x**2 + x*y, x, y, domain='ZZ')

        >>> print((x**2 + x*y).as_poly(x, y))
        Poly(x**2 + x*y, x, y, domain='ZZ')

        >>> print((x**2 + sin(y)).as_poly(x, y))
        None

        N)rT   rv   r9   )r   rV   r{   polys       ra   as_polyzPoly.as_polyQ  s<     	,t,t,D<< 		s       	,,c                     t        | j                  d      r| j                  j                         }nt        | d      | j	                  |      S )a  
        Convert algebraic coefficients to rationals.

        Examples
        ========

        >>> from sympy import Poly, I
        >>> from sympy.abc import x

        >>> Poly(x**2 + I*x + 1, x, extension=I).lift()
        Poly(x**4 + 3*x**2 + 1, x, domain='QQ')

        lift)r  rg   rG  r4   r   r  s     ra   rG  z	Poly.liftk  s<     155&!UUZZ\F'622uuV}rd   c                     t        | j                  d      r| j                  j                         \  }}nt        | d      || j	                  |      fS )a+  
        Reduce degree of ``f`` by mapping ``x_i**m`` to ``y_i``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x**6*y**2 + x**3 + 1, x, y).deflate()
        ((3, 2), Poly(x**2*y + x + 1, x, y, domain='ZZ'))

        deflate)r  rg   rI  r4   r   r\   r   r_   s      ra   rI  zPoly.deflate  sE     155)$IAv'955!%%-rd   c                    | j                   j                  }|j                  r| S |j                  st	        d|z        t        | j                   d      r| j                   j                  |      }nt        | d      |r|j                  | j                  z   }n| j                  |j                  z   } | j                  |g| S )a  
        Inject ground domain generators into ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> f = Poly(x**2*y + x*y**3 + x*y + 1, x)

        >>> f.inject()
        Poly(x**2*y + x*y**3 + x*y + 1, x, y, domain='ZZ')
        >>> f.inject(front=True)
        Poly(y**3*x + y*x**2 + y*x + 1, y, x, domain='ZZ')

        z Cannot inject generators over %sinjectfront)rg   r   is_Numericalrv   r5   r  rL  r4   r   rV   r   )r\   rN  r   r_   rV   s        ra   rL  zPoly.inject  s    $ eeiiH@3FGG155(#UU\\\.F'844;;'D66CKK'DquuV#d##rd   c                    | j                   j                  }|j                  st        d|z        t	        |      }| j
                  d| |k(  r| j
                  |d d}}n1| j
                  | d |k(  r| j
                  d|  d}}nt        d       |j                  | }t        | j                   d      r| j                   j                  ||      }nt        | d       | j                  |g| S )a  
        Eject selected generators into the ground domain.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> f = Poly(x**2*y + x*y**3 + x*y + 1, x, y)

        >>> f.eject(x)
        Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]')
        >>> f.eject(y)
        Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]')

        zCannot eject generators over %sNTFz'can only eject front or back generatorsejectrM  )rg   r   rO  r5   r   rV   rn   rL  r  rQ  r4   r   )r\   rV   r   k_gensrN  r_   s          ra   rQ  z
Poly.eject  s    $ eeii?#EFFI66"1:66!":t5EVVQBC[D 66#A2;5E%9; ; cjj$155'"UU[[E[2F'733quuV$e$$rd   c                     t        | j                  d      r| j                  j                         \  }}nt        | d      || j	                  |      fS )a  
        Remove GCD of terms from the polynomial ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x**6*y**2 + x**3*y, x, y).terms_gcd()
        ((3, 1), Poly(x**3*y + 1, x, y, domain='ZZ'))

        	terms_gcd)r  rg   rU  r4   r   rJ  s      ra   rU  zPoly.terms_gcd  sF     155+&)IAv';77!%%-rd   c                     t        | j                  d      r| j                  j                  |      }nt        | d      | j	                  |      S )z
        Add an element of the ground domain to ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x + 1).add_ground(2)
        Poly(x + 3, x, domain='ZZ')

        
add_ground)r  rg   rW  r4   r   r\   r   r_   s      ra   rW  zPoly.add_ground  A     155,'UU%%e,F'<88uuV}rd   c                     t        | j                  d      r| j                  j                  |      }nt        | d      | j	                  |      S )z
        Subtract an element of the ground domain from ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x + 1).sub_ground(2)
        Poly(x - 1, x, domain='ZZ')

        
sub_ground)r  rg   r[  r4   r   rX  s      ra   r[  zPoly.sub_ground  rY  rd   c                     t        | j                  d      r| j                  j                  |      }nt        | d      | j	                  |      S )z
        Multiply ``f`` by a an element of the ground domain.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x + 1).mul_ground(2)
        Poly(2*x + 2, x, domain='ZZ')

        
mul_ground)r  rg   r]  r4   r   rX  s      ra   r]  zPoly.mul_ground#  rY  rd   c                     t        | j                  d      r| j                  j                  |      }nt        | d      | j	                  |      S )aO  
        Quotient of ``f`` by a an element of the ground domain.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(2*x + 4).quo_ground(2)
        Poly(x + 2, x, domain='ZZ')

        >>> Poly(2*x + 3).quo_ground(2)
        Poly(x + 1, x, domain='ZZ')

        
quo_ground)r  rg   r_  r4   r   rX  s      ra   r_  zPoly.quo_ground8  sA    " 155,'UU%%e,F'<88uuV}rd   c                     t        | j                  d      r| j                  j                  |      }nt        | d      | j	                  |      S )a  
        Exact quotient of ``f`` by a an element of the ground domain.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(2*x + 4).exquo_ground(2)
        Poly(x + 2, x, domain='ZZ')

        >>> Poly(2*x + 3).exquo_ground(2)
        Traceback (most recent call last):
        ...
        ExactQuotientFailed: 2 does not divide 3 in ZZ

        exquo_ground)r  rg   ra  r4   r   rX  s      ra   ra  zPoly.exquo_groundP  sA    & 155.)UU''.F'>::uuV}rd   c                     t        | j                  d      r| j                  j                         }nt        | d      | j	                  |      S )z
        Make all coefficients in ``f`` positive.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 - 1, x).abs()
        Poly(x**2 + 1, x, domain='ZZ')

        abs)r  rg   rc  r4   r   r  s     ra   rc  zPoly.absj  s<     155% UUYY[F'511uuV}rd   c                     t        | j                  d      r| j                  j                         }nt        | d      | j	                  |      S )a4  
        Negate all coefficients in ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 - 1, x).neg()
        Poly(-x**2 + 1, x, domain='ZZ')

        >>> -Poly(x**2 - 1, x)
        Poly(-x**2 + 1, x, domain='ZZ')

        neg)r  rg   re  r4   r   r  s     ra   re  zPoly.neg  <    " 155% UUYY[F'511uuV}rd   c                     t        |      }|j                  s| j                  |      S | j                  |      \  }}}}t	        | j
                  d      r|j                  |      }nt        | d       ||      S )a[  
        Add two polynomials ``f`` and ``g``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 + 1, x).add(Poly(x - 2, x))
        Poly(x**2 + x - 1, x, domain='ZZ')

        >>> Poly(x**2 + 1, x) + Poly(x - 2, x)
        Poly(x**2 + x - 1, x, domain='ZZ')

        r  )r"   rv   rW  r   r  rg   r  r4   r\   r]   r   r   r   r   r_   s          ra   r  zPoly.add  i    " AJyy<<?"xx{31155% UU1XF'5116{rd   c                     t        |      }|j                  s| j                  |      S | j                  |      \  }}}}t	        | j
                  d      r|j                  |      }nt        | d       ||      S )a`  
        Subtract two polynomials ``f`` and ``g``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 + 1, x).sub(Poly(x - 2, x))
        Poly(x**2 - x + 3, x, domain='ZZ')

        >>> Poly(x**2 + 1, x) - Poly(x - 2, x)
        Poly(x**2 - x + 3, x, domain='ZZ')

        sub)r"   rv   r[  r   r  rg   rk  r4   rh  s          ra   rk  zPoly.sub  ri  rd   c                     t        |      }|j                  s| j                  |      S | j                  |      \  }}}}t	        | j
                  d      r|j                  |      }nt        | d       ||      S )ap  
        Multiply two polynomials ``f`` and ``g``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 + 1, x).mul(Poly(x - 2, x))
        Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ')

        >>> Poly(x**2 + 1, x)*Poly(x - 2, x)
        Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ')

        r   )r"   rv   r]  r   r  rg   r   r4   rh  s          ra   r   zPoly.mul  ri  rd   c                     t        | j                  d      r| j                  j                         }nt        | d      | j	                  |      S )a3  
        Square a polynomial ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x - 2, x).sqr()
        Poly(x**2 - 4*x + 4, x, domain='ZZ')

        >>> Poly(x - 2, x)**2
        Poly(x**2 - 4*x + 4, x, domain='ZZ')

        sqr)r  rg   rn  r4   r   r  s     ra   rn  zPoly.sqr  rf  rd   c                     t        |      }t        | j                  d      r| j                  j                  |      }nt	        | d      | j                  |      S )aX  
        Raise ``f`` to a non-negative power ``n``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x - 2, x).pow(3)
        Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ')

        >>> Poly(x - 2, x)**3
        Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ')

        pow)r(  r  rg   rp  r4   r   r\   r*  r_   s      ra   rp  zPoly.pow  sG    " F155% UUYYq\F'511uuV}rd   c                     | j                  |      \  }}}}t        | j                  d      r|j                  |      \  }}nt	        | d       ||       ||      fS )a#  
        Polynomial pseudo-division of ``f`` by ``g``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 + 1, x).pdiv(Poly(2*x - 4, x))
        (Poly(2*x + 4, x, domain='ZZ'), Poly(20, x, domain='ZZ'))

        pdiv)r   r  rg   rs  r4   )r\   r]   r   r   r   r   qrs           ra   rs  z	Poly.pdiv&  sW     xx{31155&!66!9DAq'6221vs1v~rd   c                     | j                  |      \  }}}}t        | j                  d      r|j                  |      }nt	        | d       ||      S )aN  
        Polynomial pseudo-remainder of ``f`` by ``g``.

        Caveat: The function prem(f, g, x) can be safely used to compute
          in Z[x] _only_ subresultant polynomial remainder sequences (prs's).

          To safely compute Euclidean and Sturmian prs's in Z[x]
          employ anyone of the corresponding functions found in
          the module sympy.polys.subresultants_qq_zz. The functions
          in the module with suffix _pg compute prs's in Z[x] employing
          rem(f, g, x), whereas the functions with suffix _amv
          compute prs's in Z[x] employing rem_z(f, g, x).

          The function rem_z(f, g, x) differs from prem(f, g, x) in that
          to compute the remainder polynomials in Z[x] it premultiplies
          the divident times the absolute value of the leading coefficient
          of the divisor raised to the power degree(f, x) - degree(g, x) + 1.


        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 + 1, x).prem(Poly(2*x - 4, x))
        Poly(20, x, domain='ZZ')

        prem)r   r  rg   rw  r4   rh  s          ra   rw  z	Poly.prem=  sK    < xx{31155&!VVAYF'6226{rd   c                     | j                  |      \  }}}}t        | j                  d      r|j                  |      }nt	        | d       ||      S )a  
        Polynomial pseudo-quotient of ``f`` by ``g``.

        See the Caveat note in the function prem(f, g).

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 + 1, x).pquo(Poly(2*x - 4, x))
        Poly(2*x + 4, x, domain='ZZ')

        >>> Poly(x**2 - 1, x).pquo(Poly(2*x - 2, x))
        Poly(2*x + 2, x, domain='ZZ')

        pquo)r   r  rg   ry  r4   rh  s          ra   ry  z	Poly.pquod  sK    & xx{31155&!VVAYF'6226{rd   c                 &   | j                  |      \  }}}}t        | j                  d      r	 |j                  |      }nt        | d       ||      S # t        $ r3}|j                  | j                         |j                               d}~ww xY w)a  
        Polynomial exact pseudo-quotient of ``f`` by ``g``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 - 1, x).pexquo(Poly(2*x - 2, x))
        Poly(2*x + 2, x, domain='ZZ')

        >>> Poly(x**2 + 1, x).pexquo(Poly(2*x - 4, x))
        Traceback (most recent call last):
        ...
        ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1

        pexquoN)r   r  rg   r{  r;   r   rZ   r4   )r\   r]   r   r   r   r   r_   excs           ra   r{  zPoly.pexquo  s    & xx{31155(#8! (8446{ ' 8ggaiik199;778s   A 	B.BBc                    | j                  |      \  }}}}d}|r:|j                  r.|j                  s"|j                         |j                         }}d}t	        | j
                  d      r|j                  |      \  }}	nt        | d      |r%	 |j                         |	j                         }}
|
|}	} ||       ||	      fS # t        $ r Y w xY w)a  
        Polynomial division with remainder of ``f`` by ``g``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x))
        (Poly(1/2*x + 1, x, domain='QQ'), Poly(5, x, domain='QQ'))

        >>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x), auto=False)
        (Poly(0, x, domain='ZZ'), Poly(x**2 + 1, x, domain='ZZ'))

        FTdiv)
r   is_Ringis_Fieldr   r  rg   r~  r4   r  r6   )r\   r]   autor   r   r   r   r%  rt  ru  QRs               ra   r~  zPoly.div  s    " !S!QCKK::<qAG155% 558DAq'511yy{AIIK1 !11vs1v~ " s    C 	CCc                 f   | j                  |      \  }}}}d}|r:|j                  r.|j                  s"|j                         |j                         }}d}t	        | j
                  d      r|j                  |      }nt        | d      |r	 |j                         } ||      S # t        $ r Y w xY w)ao  
        Computes the polynomial remainder of ``f`` by ``g``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x))
        Poly(5, x, domain='ZZ')

        >>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x), auto=False)
        Poly(x**2 + 1, x, domain='ZZ')

        FTrem)
r   r  r  r   r  rg   r  r4   r  r6   )	r\   r]   r  r   r   r   r   r%  ru  s	            ra   r  zPoly.rem      " !S!QCKK::<qAG155% aA'511IIK 1v "    B$ $	B0/B0c                 f   | j                  |      \  }}}}d}|r:|j                  r.|j                  s"|j                         |j                         }}d}t	        | j
                  d      r|j                  |      }nt        | d      |r	 |j                         } ||      S # t        $ r Y w xY w)aa  
        Computes polynomial quotient of ``f`` by ``g``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 + 1, x).quo(Poly(2*x - 4, x))
        Poly(1/2*x + 1, x, domain='QQ')

        >>> Poly(x**2 - 1, x).quo(Poly(x - 1, x))
        Poly(x + 1, x, domain='ZZ')

        FTquo)
r   r  r  r   r  rg   r  r4   r  r6   )	r\   r]   r  r   r   r   r   r%  rt  s	            ra   r  zPoly.quo  r  r  c                    | j                  |      \  }}}}d}|r:|j                  r.|j                  s"|j                         |j                         }}d}t	        | j
                  d      r	 |j                  |      }nt        | d      |r	 |j                         } ||      S # t        $ r3}	|	j                  | j                         |j                               d}	~	ww xY w# t        $ r Y Rw xY w)a  
        Computes polynomial exact quotient of ``f`` by ``g``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 - 1, x).exquo(Poly(x - 1, x))
        Poly(x + 1, x, domain='ZZ')

        >>> Poly(x**2 + 1, x).exquo(Poly(2*x - 4, x))
        Traceback (most recent call last):
        ...
        ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1

        FTexquoN)r   r  r  r   r  rg   r  r;   r   rZ   r4   r  r6   )
r\   r]   r  r   r   r   r   r%  rt  r|  s
             ra   r  z
Poly.exquo  s    & !S!QCKK::<qAG155'"8GGAJ (733IIK 1v ' 8ggaiik199;778 " s*   ,B% C$ %	C!..CC!$	C0/C0c                 *   t        |t              rDt        | j                        }| |cxk  r|k  rn n|dk  r||z   S |S t	        d|d|d|      	 | j                  j                  t        |            S # t        $ r t	        d|z        w xY w)z3Returns level associated with the given generator. r   -z
 <= gen < z expected, got z"a valid generator expected, got %s)rS   r(  r   rV   r9   r   r"   r  )r\   r   r:  s      ra   r  zPoly._gen_to_level:  s    c3[Fw#&&7!C<'J%'-vs'< = =@vv||GCL11 @%83>@ @@s   #A: :Bc                     | j                  |      }t        | j                  d      r2| j                  j                  |      }|dk  rt        j
                  }|S t        | d      )au  
        Returns degree of ``f`` in ``x_j``.

        The degree of 0 is negative infinity.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x**2 + y*x + 1, x, y).degree()
        2
        >>> Poly(x**2 + y*x + y, x, y).degree(y)
        1
        >>> Poly(0, x).degree()
        -oo

        degreer   )r  r  rg   r  r   NegativeInfinityr4   )r\   r   r   ds       ra   r  zPoly.degreeN  sU    ( OOC 155(#QA1u&&H'844rd   c                 z    t        | j                  d      r| j                  j                         S t        | d      )z
        Returns a list of degrees of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x**2 + y*x + 1, x, y).degree_list()
        (2, 1)

        degree_list)r  rg   r  r4   r   s    ra   r  zPoly.degree_listl  s2     155-(55$$&&'=99rd   c                 z    t        | j                  d      r| j                  j                         S t        | d      )a  
        Returns the total degree of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x**2 + y*x + 1, x, y).total_degree()
        2
        >>> Poly(x + y**5, x, y).total_degree()
        5

        total_degree)r  rg   r  r4   r   s    ra   r  zPoly.total_degree  s2      155.)55%%'''>::rd   c                    t        |t              st        dt        |      z        || j                  v r(| j                  j                  |      }| j                  }n%t        | j                        }| j                  |fz   }t        | j                  d      r,| j                  | j                  j                  |      |      S t        | d      )a  
        Returns the homogeneous polynomial of ``f``.

        A homogeneous polynomial is a polynomial whose all monomials with
        non-zero coefficients have the same total degree. If you only
        want to check if a polynomial is homogeneous, then use
        :func:`Poly.is_homogeneous`. If you want not only to check if a
        polynomial is homogeneous but also compute its homogeneous order,
        then use :func:`Poly.homogeneous_order`.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y, z

        >>> f = Poly(x**5 + 2*x**2*y**2 + 9*x*y**3)
        >>> f.homogenize(z)
        Poly(x**5 + 2*x**2*y**2*z + 9*x*y**3*z, x, y, z, domain='ZZ')

        z``Symbol`` expected, got %s
homogenizer   homogeneous_order)rS   r!   	TypeErrorru   rV   r   r   r  rg   r   r  r4   )r\   sr   rV   s       ra   r  zPoly.homogenize  s    , !V$9DGCDD;QA66DAFFA66QD=D155,'55))!,4588#A':;;rd   c                 z    t        | j                  d      r| j                  j                         S t        | d      )a-  
        Returns the homogeneous order of ``f``.

        A homogeneous polynomial is a polynomial whose all monomials with
        non-zero coefficients have the same total degree. This degree is
        the homogeneous order of ``f``. If you only want to check if a
        polynomial is homogeneous, then use :func:`Poly.is_homogeneous`.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> f = Poly(x**5 + 2*x**3*y**2 + 9*x*y**4)
        >>> f.homogeneous_order()
        5

        r  )r  rg   r  r4   r   s    ra   r  zPoly.homogeneous_order  s4    ( 155-.55**,,'+>??rd   c                     || j                  |      d   S t        | j                  d      r| j                  j                         }nt	        | d      | j                  j
                  j                  |      S )z
        Returns the leading coefficient of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(4*x**3 + 2*x**2 + 3*x, x).LC()
        4

        r   LC)r   r  rg   r  r4   r   r   )r\   ri   r_   s      ra   r  zPoly.LC  s`     88E?1%%155$UUXXZF'400uuyy!!&))rd   c                     t        | j                  d      r| j                  j                         }nt        | d      | j                  j                  j                  |      S )z
        Returns the trailing coefficient of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**3 + 2*x**2 + 3*x, x).TC()
        0

        TC)r  rg   r  r4   r   r   r  s     ra   r  zPoly.TC  sG     155$UUXXZF'400uuyy!!&))rd   c                 n    t        | j                  d      r| j                  |      d   S t        | d      )z
        Returns the last non-zero coefficient of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**3 + 2*x**2 + 3*x, x).EC()
        3

        r   EC)r  rg   r   r4   r.  s     ra   r  zPoly.EC  s2     155(#88E?2&&'400rd   c                 \     | j                   t        || j                        j                   S )aE  
        Returns the coefficient of ``monom`` in ``f`` if there, else None.

        Examples
        ========

        >>> from sympy import Poly, exp
        >>> from sympy.abc import x, y

        >>> p = Poly(24*x*y*exp(8) + 23*x, x, y)

        >>> p.coeff_monomial(x)
        23
        >>> p.coeff_monomial(y)
        0
        >>> p.coeff_monomial(x*y)
        24*exp(8)

        Note that ``Expr.coeff()`` behaves differently, collecting terms
        if possible; the Poly must be converted to an Expr to use that
        method, however:

        >>> p.as_expr().coeff(x)
        24*y*exp(8) + 23
        >>> p.as_expr().coeff(y)
        24*x*exp(8)
        >>> p.as_expr().coeff(x*y)
        24*exp(8)

        See Also
        ========
        nth: more efficient query using exponents of the monomial's generators

        )nthr/   rV   	exponents)r\   r   s     ra   coeff_monomialzPoly.coeff_monomial  s'    F quuhuaff-7788rd   c                 J   t        | j                  d      r]t        |      t        | j                        k7  rt	        d       | j                  j
                  t        t        t        |             }nt        | d      | j                  j                  j                  |      S )a.  
        Returns the ``n``-th coefficient of ``f`` where ``N`` are the
        exponents of the generators in the term of interest.

        Examples
        ========

        >>> from sympy import Poly, sqrt
        >>> from sympy.abc import x, y

        >>> Poly(x**3 + 2*x**2 + 3*x, x).nth(2)
        2
        >>> Poly(x**3 + 2*x*y**2 + y**2, x, y).nth(1, 2)
        2
        >>> Poly(4*sqrt(x)*y)
        Poly(4*y*(sqrt(x)), y, sqrt(x), domain='ZZ')
        >>> _.nth(1, 1)
        4

        See Also
        ========
        coeff_monomial

        r  z,exponent of each generator must be specified)r  rg   r   rV   r  r  rt   r   r(  r4   r   r   )r\   Nr_   s      ra   r  zPoly.nth4  sw    2 155% 1vQVV$ !OPPQUUYYSa[ 12F'511uuyy!!&))rd   c                     t        d      )NzyEither convert to Expr with `as_expr` method to use Expr's coeff method or else use the `coeff_monomial` method of Polys.rn   )r\   r  r*  rights       ra   r   z
Poly.coeffV  s     "01 	1rd   c                 R    t        | j                  |      d   | j                        S )a  
        Returns the leading monomial of ``f``.

        The Leading monomial signifies the monomial having
        the highest power of the principal generator in the
        expression f.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LM()
        x**2*y**0

        r   r/   r   rV   r.  s     ra   LMzPoly.LMb  s"    $ *AFF33rd   c                 R    t        | j                  |      d   | j                        S )z
        Returns the last non-zero monomial of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).EM()
        x**0*y**1

        r  r  r.  s     ra   EMzPoly.EMv  s"     +QVV44rd   c                 `    | j                  |      d   \  }}t        || j                        |fS )a  
        Returns the leading term of ``f``.

        The Leading term signifies the term having
        the highest power of the principal generator in the
        expression f along with its coefficient.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LT()
        (x**2*y**0, 4)

        r   r  r/   rV   r\   ri   r   r   s       ra   LTzPoly.LT  s0    $ wwu~a(uqvv&--rd   c                 `    | j                  |      d   \  }}t        || j                        |fS )z
        Returns the last non-zero term of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).ET()
        (x**0*y**1, 3)

        r  r  r  s       ra   ETzPoly.ET  s0     wwu~b)uqvv&--rd   c                     t        | j                  d      r| j                  j                         }nt        | d      | j                  j                  j                  |      S )z
        Returns maximum norm of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(-x**2 + 2*x - 3, x).max_norm()
        3

        max_norm)r  rg   r  r4   r   r   r  s     ra   r  zPoly.max_norm  sH     155*%UU^^%F':66uuyy!!&))rd   c                     t        | j                  d      r| j                  j                         }nt        | d      | j                  j                  j                  |      S )z
        Returns l1 norm of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(-x**2 + 2*x - 3, x).l1_norm()
        6

        l1_norm)r  rg   r  r4   r   r   r  s     ra   r  zPoly.l1_norm  G     155)$UU]]_F'955uuyy!!&))rd   c                    | }|j                   j                  j                  st        j                  |fS |j                         }|j                  r$|j                   j                  j                         }t        |j                   d      r|j                   j                         \  }}nt        |d      |j                  |      |j                  |      }}|r|j                  s||fS ||j                         fS )a  
        Clear denominators, but keep the ground domain.

        Examples
        ========

        >>> from sympy import Poly, S, QQ
        >>> from sympy.abc import x

        >>> f = Poly(x/2 + S(1)/3, x, domain=QQ)

        >>> f.clear_denoms()
        (6, Poly(3*x + 2, x, domain='QQ'))
        >>> f.clear_denoms(convert=True)
        (6, Poly(3*x + 2, x, domain='ZZ'))

        clear_denoms)rg   r   r  r   Oner   has_assoc_Ringget_ringr  r  r4   r   r   r  )r   r   r\   r   r   r_   s         ra   r  zPoly.clear_denoms  s    $ uuyy!!55!8Olln%%))$$&C155.)EE..0ME6'>::<<&fqc00!8O!))+%%rd   c                 *   | }|j                  |      \  }}}} ||      } ||      }|j                  r|j                  s||fS |j                  d      \  }}|j                  d      \  }}|j	                  |      }|j	                  |      }||fS )a  
        Clear denominators in a rational function ``f/g``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> f = Poly(x**2/y + 1, x)
        >>> g = Poly(x**3 + y, x)

        >>> p, q = f.rat_clear_denoms(g)

        >>> p
        Poly(x**2 + y, x, domain='ZZ[y]')
        >>> q
        Poly(y*x**3 + y**2, x, domain='ZZ[y]')

        Tr   )r   r  r  r  r]  )r   r]   r\   r   r   abs          ra   rat_clear_denomszPoly.rat_clear_denoms  s    * !S!QFF!3!3a4K~~d~+1~~d~+1LLOLLO!trd   c                    | }|j                  dd      r0|j                  j                  j                  r|j	                         }t        |j                  d      r|s+|j                  |j                  j                  d            S |j                  }|D ]F  }t        |t              r|\  }}n|d}}|j                  t        |      |j                  |            }H |j                  |      S t        |d      )a  
        Computes indefinite integral of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x**2 + 2*x + 1, x).integrate()
        Poly(1/3*x**3 + x**2 + x, x, domain='QQ')

        >>> Poly(x*y**2 + x, x, y).integrate((0, 1), (1, 0))
        Poly(1/2*x**2*y**2 + 1/2*x**2, x, y, domain='QQ')

        r  T	integrater   r)  )getrg   r   r  r   r  r   r  rS   r7  r(  r  r4   )r   specsr{   r\   rg   specr   r)  s           ra   r  zPoly.integrate$	  s    " 88FD!aeeii&7&7

A155+&uuQUU__q_122%%C BdE*!FC!1CmmCFAOOC,@AB 55:';77rd   c                    |j                  dd      st        | g|i |S t        | j                  d      r|s+| j	                  | j                  j                  d            S | j                  }|D ]F  }t        |t              r|\  }}n|d}}|j                  t        |      | j                  |            }H | j	                  |      S t        | d      )aX  
        Computes partial derivative of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x**2 + 2*x + 1, x).diff()
        Poly(2*x + 2, x, domain='ZZ')

        >>> Poly(x*y**2 + x, x, y).diff((0, 0), (1, 1))
        Poly(2*x*y, x, y, domain='ZZ')

        rk   Tdiffr   r  )r  r   r  rg   r   r  rS   r7  r(  r  r4   )r\   r  r  rg   r  r   r)  s          ra   r  z	Poly.diffL	  s    " zz*d+a2%2622155&!uuQUUZZ!Z_--%%C =dE*!FC!1Chhs1vqs';<= 55:'622rd   c                    | }|t        |t              r.|}|j                         D ]  \  }}|j                  ||      } |S t        |t        t
        f      r`|}t        |      t        |j                        kD  rt        d      t        |j                  |      D ]  \  }}|j                  ||      } |S d|}}	n|j                  |      }	t        |j                  d      st        |d      	 |j                  j                  ||	      }
|j-                  |
|	      S # t        $ r |s%t        d|d|j                  j                         t#        |g      \  }\  }|j%                         j'                  ||j                        }|j)                  |      }|j+                  ||      }|j                  j                  ||	      }
Y w xY w)a  
        Evaluate ``f`` at ``a`` in the given variable.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y, z

        >>> Poly(x**2 + 2*x + 3, x).eval(2)
        11

        >>> Poly(2*x*y + 3*x + y + 2, x, y).eval(x, 2)
        Poly(5*y + 8, y, domain='ZZ')

        >>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z)

        >>> f.eval({x: 2})
        Poly(5*y + 2*z + 6, y, z, domain='ZZ')
        >>> f.eval({x: 2, y: 5})
        Poly(2*z + 31, z, domain='ZZ')
        >>> f.eval({x: 2, y: 5, z: 7})
        45

        >>> f.eval((2, 5))
        Poly(2*z + 31, z, domain='ZZ')
        >>> f(2, 5)
        Poly(2*z + 31, z, domain='ZZ')

        ztoo many values providedr   r   zCannot evaluate at r   r   )rS   rq   r   r   r7  rt   r   rV   r  r   r  r  rg   r4   r6   r5   r   r(   r   unify_with_symbolsr   r   r   )r   r  r  r  r\   rA  r   rB  valuesr   r_   a_domain
new_domains                ra   r   z	Poly.evalt	  s   > 9!T"")--/ +JCsE*A+ At}-v;QVV,$%?@@"%afff"5 +JCsE*A+ !1"Aquuf%'622	*UUZZ1%F uuVAu&&  
	*!1aeeii"PQQ 0! 5#1\\^>>xP
LL,&&q(3Aq)
	*s   2D! !B*GGc                 $    | j                  |      S )az  
        Evaluate ``f`` at the give values.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y, z

        >>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z)

        >>> f(2)
        Poly(5*y + 2*z + 6, y, z, domain='ZZ')
        >>> f(2, 5)
        Poly(2*z + 31, z, domain='ZZ')
        >>> f(2, 5, 7)
        45

        )r   )r\   r  s     ra   __call__zPoly.__call__	  s    ( vvf~rd   c                    | j                  |      \  }}}}|r,|j                  r |j                         |j                         }}t        | j                  d      r|j                  |      \  }}nt        | d       ||       ||      fS )a  
        Half extended Euclidean algorithm of ``f`` and ``g``.

        Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15
        >>> g = x**3 + x**2 - 4*x - 4

        >>> Poly(f).half_gcdex(Poly(g))
        (Poly(-1/5*x + 3/5, x, domain='QQ'), Poly(x + 1, x, domain='QQ'))

        
half_gcdex)r   r  r   r  rg   r  r4   )	r\   r]   r  r   r   r   r   r  hs	            ra   r  zPoly.half_gcdex	  su    & !S!QCKK::<qA155,'<<?DAq'<881vs1v~rd   c                 (   | j                  |      \  }}}}|r,|j                  r |j                         |j                         }}t        | j                  d      r|j                  |      \  }}}	nt        | d       ||       ||       ||	      fS )a  
        Extended Euclidean algorithm of ``f`` and ``g``.

        Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15
        >>> g = x**3 + x**2 - 4*x - 4

        >>> Poly(f).gcdex(Poly(g))
        (Poly(-1/5*x + 3/5, x, domain='QQ'),
         Poly(1/5*x**2 - 6/5*x + 2, x, domain='QQ'),
         Poly(x + 1, x, domain='QQ'))

        gcdex)r   r  r   r  rg   r  r4   )
r\   r]   r  r   r   r   r   r  tr  s
             ra   r  z
Poly.gcdex	  s~    * !S!QCKK::<qA155'"ggajGAq!'7331vs1vs1v%%rd   c                    | j                  |      \  }}}}|r,|j                  r |j                         |j                         }}t        | j                  d      r|j                  |      }nt        | d       ||      S )a  
        Invert ``f`` modulo ``g`` when possible.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 - 1, x).invert(Poly(2*x - 1, x))
        Poly(-4/3, x, domain='QQ')

        >>> Poly(x**2 - 1, x).invert(Poly(x - 1, x))
        Traceback (most recent call last):
        ...
        NotInvertible: zero divisor

        invert)r   r  r   r  rg   r  r4   )r\   r]   r  r   r   r   r   r_   s           ra   r  zPoly.invert
  si    & !S!QCKK::<qA155(#XXa[F'8446{rd   c                     t        | j                  d      r%| j                  j                  t        |            }nt	        | d      | j                  |      S )ad  
        Compute ``f**(-1)`` mod ``x**n``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(1, x).revert(2)
        Poly(1, x, domain='ZZ')

        >>> Poly(1 + x, x).revert(1)
        Poly(1, x, domain='ZZ')

        >>> Poly(x**2 - 2, x).revert(2)
        Traceback (most recent call last):
        ...
        NotReversible: only units are reversible in a ring

        >>> Poly(1/x, x).revert(1)
        Traceback (most recent call last):
        ...
        PolynomialError: 1/x contains an element of the generators set

        revert)r  rg   r  r(  r4   r   rq  s      ra   r  zPoly.revert4
  sC    6 155(#UU\\#a&)F'844uuV}rd   c                     | j                  |      \  }}}}t        | j                  d      r|j                  |      }nt	        | d      t        t        ||            S )ad  
        Computes the subresultant PRS of ``f`` and ``g``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 + 1, x).subresultants(Poly(x**2 - 1, x))
        [Poly(x**2 + 1, x, domain='ZZ'),
         Poly(x**2 - 1, x, domain='ZZ'),
         Poly(-2, x, domain='ZZ')]

        subresultants)r   r  rg   r  r4   rt   r   rh  s          ra   r  zPoly.subresultantsV
  sT      xx{31155/*__Q'F'?;;CV$%%rd   c                    | j                  |      \  }}}}t        | j                  d      r+|r|j                  ||      \  }}n|j                  |      }nt	        | d      |r ||d      t        t        |            fS  ||d      S )a  
        Computes the resultant of ``f`` and ``g`` via PRS.

        If includePRS=True, it includes the subresultant PRS in the result.
        Because the PRS is used to calculate the resultant, this is more
        efficient than calling :func:`subresultants` separately.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> f = Poly(x**2 + 1, x)

        >>> f.resultant(Poly(x**2 - 1, x))
        4
        >>> f.resultant(Poly(x**2 - 1, x), includePRS=True)
        (4, [Poly(x**2 + 1, x, domain='ZZ'), Poly(x**2 - 1, x, domain='ZZ'),
             Poly(-2, x, domain='ZZ')])

        	resultant
includePRSr   r  )r   r  rg   r  r4   rt   r   )	r\   r]   r  r   r   r   r   r_   r  s	            ra   r  zPoly.resultanto
  s    . xx{31155+&KKjKA	Q';77q)4C+<==6!$$rd   c                     t        | j                  d      r| j                  j                         }nt        | d      | j	                  |d      S )z
        Computes the discriminant of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 + 2*x + 3, x).discriminant()
        -8

        discriminantr   r  )r  rg   r  r4   r   r  s     ra   r  zPoly.discriminant
  sD     155.)UU'')F'>::uuVAu&&rd   c                      ddl m}  || |      S )a  Compute the *dispersion set* of two polynomials.

        For two polynomials `f(x)` and `g(x)` with `\deg f > 0`
        and `\deg g > 0` the dispersion set `\operatorname{J}(f, g)` is defined as:

        .. math::
            \operatorname{J}(f, g)
            & := \{a \in \mathbb{N}_0 | \gcd(f(x), g(x+a)) \neq 1\} \\
            &  = \{a \in \mathbb{N}_0 | \deg \gcd(f(x), g(x+a)) \geq 1\}

        For a single polynomial one defines `\operatorname{J}(f) := \operatorname{J}(f, f)`.

        Examples
        ========

        >>> from sympy import poly
        >>> from sympy.polys.dispersion import dispersion, dispersionset
        >>> from sympy.abc import x

        Dispersion set and dispersion of a simple polynomial:

        >>> fp = poly((x - 3)*(x + 3), x)
        >>> sorted(dispersionset(fp))
        [0, 6]
        >>> dispersion(fp)
        6

        Note that the definition of the dispersion is not symmetric:

        >>> fp = poly(x**4 - 3*x**2 + 1, x)
        >>> gp = fp.shift(-3)
        >>> sorted(dispersionset(fp, gp))
        [2, 3, 4]
        >>> dispersion(fp, gp)
        4
        >>> sorted(dispersionset(gp, fp))
        []
        >>> dispersion(gp, fp)
        -oo

        Computing the dispersion also works over field extensions:

        >>> from sympy import sqrt
        >>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>')
        >>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>')
        >>> sorted(dispersionset(fp, gp))
        [2]
        >>> sorted(dispersionset(gp, fp))
        [1, 4]

        We can even perform the computations for polynomials
        having symbolic coefficients:

        >>> from sympy.abc import a
        >>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x)
        >>> sorted(dispersionset(fp))
        [0, 1]

        See Also
        ========

        dispersion

        References
        ==========

        1. [ManWright94]_
        2. [Koepf98]_
        3. [Abramov71]_
        4. [Man93]_
        r   )dispersionset)sympy.polys.dispersionr  )r\   r]   r  s      ra   r  zPoly.dispersionset
  s    P 	9Q""rd   c                      ddl m}  || |      S )a  Compute the *dispersion* of polynomials.

        For two polynomials `f(x)` and `g(x)` with `\deg f > 0`
        and `\deg g > 0` the dispersion `\operatorname{dis}(f, g)` is defined as:

        .. math::
            \operatorname{dis}(f, g)
            & := \max\{ J(f,g) \cup \{0\} \} \\
            &  = \max\{ \{a \in \mathbb{N} | \gcd(f(x), g(x+a)) \neq 1\} \cup \{0\} \}

        and for a single polynomial `\operatorname{dis}(f) := \operatorname{dis}(f, f)`.

        Examples
        ========

        >>> from sympy import poly
        >>> from sympy.polys.dispersion import dispersion, dispersionset
        >>> from sympy.abc import x

        Dispersion set and dispersion of a simple polynomial:

        >>> fp = poly((x - 3)*(x + 3), x)
        >>> sorted(dispersionset(fp))
        [0, 6]
        >>> dispersion(fp)
        6

        Note that the definition of the dispersion is not symmetric:

        >>> fp = poly(x**4 - 3*x**2 + 1, x)
        >>> gp = fp.shift(-3)
        >>> sorted(dispersionset(fp, gp))
        [2, 3, 4]
        >>> dispersion(fp, gp)
        4
        >>> sorted(dispersionset(gp, fp))
        []
        >>> dispersion(gp, fp)
        -oo

        Computing the dispersion also works over field extensions:

        >>> from sympy import sqrt
        >>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>')
        >>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>')
        >>> sorted(dispersionset(fp, gp))
        [2]
        >>> sorted(dispersionset(gp, fp))
        [1, 4]

        We can even perform the computations for polynomials
        having symbolic coefficients:

        >>> from sympy.abc import a
        >>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x)
        >>> sorted(dispersionset(fp))
        [0, 1]

        See Also
        ========

        dispersionset

        References
        ==========

        1. [ManWright94]_
        2. [Koepf98]_
        3. [Abramov71]_
        4. [Man93]_
        r   )
dispersion)r  r  )r\   r]   r  s      ra   r  zPoly.dispersion
  s    P 	6!Qrd   c                     | j                  |      \  }}}}t        | j                  d      r|j                  |      \  }}}nt	        | d       ||       ||       ||      fS )a#  
        Returns the GCD of ``f`` and ``g`` and their cofactors.

        Returns polynomials ``(h, cff, cfg)`` such that ``h = gcd(f, g)``, and
        ``cff = quo(f, h)`` and ``cfg = quo(g, h)`` are, so called, cofactors
        of ``f`` and ``g``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 - 1, x).cofactors(Poly(x**2 - 3*x + 2, x))
        (Poly(x - 1, x, domain='ZZ'),
         Poly(x + 1, x, domain='ZZ'),
         Poly(x - 2, x, domain='ZZ'))

        	cofactors)r   r  rg   r  r4   )	r\   r]   r   r   r   r   r  cffcfgs	            ra   r  zPoly.cofactors?  s`    ( xx{31155+&++a.KAsC';771vs3xS))rd   c                     | j                  |      \  }}}}t        | j                  d      r|j                  |      }nt	        | d       ||      S )a  
        Returns the polynomial GCD of ``f`` and ``g``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 - 1, x).gcd(Poly(x**2 - 3*x + 2, x))
        Poly(x - 1, x, domain='ZZ')

        gcd)r   r  rg   r  r4   rh  s          ra   r  zPoly.gcd\  K     xx{31155% UU1XF'5116{rd   c                     | j                  |      \  }}}}t        | j                  d      r|j                  |      }nt	        | d       ||      S )a  
        Returns polynomial LCM of ``f`` and ``g``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 - 1, x).lcm(Poly(x**2 - 3*x + 2, x))
        Poly(x**3 - 2*x**2 - x + 2, x, domain='ZZ')

        lcm)r   r  rg   r  r4   rh  s          ra   r  zPoly.lcms  r  rd   c                     | j                   j                  j                  |      }t        | j                   d      r| j                   j	                  |      }nt        | d      | j                  |      S )a  
        Reduce ``f`` modulo a constant ``p``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(2*x**3 + 3*x**2 + 5*x + 7, x).trunc(3)
        Poly(-x**3 - x + 1, x, domain='ZZ')

        trunc)rg   r   r   r  r  r4   r   )r\   pr_   s      ra   r  z
Poly.trunc  sV     EEIIa 155'"UU[[^F'733uuV}rd   c                    | }|r0|j                   j                  j                  r|j                         }t	        |j                   d      r|j                   j                         }nt        |d      |j                  |      S )az  
        Divides all coefficients by ``LC(f)``.

        Examples
        ========

        >>> from sympy import Poly, ZZ
        >>> from sympy.abc import x

        >>> Poly(3*x**2 + 6*x + 9, x, domain=ZZ).monic()
        Poly(x**2 + 2*x + 3, x, domain='QQ')

        >>> Poly(3*x**2 + 4*x + 2, x, domain=ZZ).monic()
        Poly(x**2 + 4/3*x + 2/3, x, domain='QQ')

        monic)rg   r   r  r   r  r  r4   r   r   r  r\   r_   s       ra   r  z
Poly.monic  s_    " AEEII%%

A155'"UU[[]F'733uuV}rd   c                     t        | j                  d      r| j                  j                         }nt        | d      | j                  j                  j                  |      S )z
        Returns the GCD of polynomial coefficients.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(6*x**2 + 8*x + 12, x).content()
        2

        content)r  rg   r  r4   r   r   r  s     ra   r  zPoly.content  r  rd   c                     t        | j                  d      r| j                  j                         \  }}nt        | d      | j                  j                  j                  |      | j                  |      fS )a  
        Returns the content and a primitive form of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(2*x**2 + 8*x + 12, x).primitive()
        (2, Poly(x**2 + 4*x + 6, x, domain='ZZ'))

        	primitive)r  rg   r  r4   r   r   r   )r\   contr_   s      ra   r  zPoly.primitive  sY     155+&55??,LD&';77uuyy!!$'v66rd   c                     | j                  |      \  }}}}t        | j                  d      r|j                  |      }nt	        | d       ||      S )a  
        Computes the functional composition of ``f`` and ``g``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 + x, x).compose(Poly(x - 1, x))
        Poly(x**2 - x, x, domain='ZZ')

        compose)r   r  rg   r  r4   rh  s          ra   r  zPoly.compose  sK     xx{31155)$YYq\F'9556{rd   c                     t        | j                  d      r| j                  j                         }nt        | d      t	        t        | j                  |            S )a=  
        Computes a functional decomposition of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**4 + 2*x**3 - x - 1, x, domain='ZZ').decompose()
        [Poly(x**2 - x - 1, x, domain='ZZ'), Poly(x**2 + x, x, domain='ZZ')]

        	decompose)r  rg   r  r4   rt   r   r   r  s     ra   r  zPoly.decompose  sE     155+&UU__&F';77Cv&''rd   c                 V    | j                  | j                  j                  |            S )am  
        Efficiently compute Taylor shift ``f(x + a)``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 - 2*x + 1, x).shift(2)
        Poly(x**2 + 2*x + 1, x, domain='ZZ')

        See Also
        ========

        shift_list: Analogous method for multivariate polynomials.
        )r   rg   shiftr\   r  s     ra   r  z
Poly.shift  s    $ uuQUU[[^$$rd   c                 V    | j                  | j                  j                  |            S )ah  
        Efficiently compute Taylor shift ``f(X + A)``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x*y, [x,y]).shift_list([1, 2]) == Poly((x+1)*(y+2), [x,y])
        True

        See Also
        ========

        shift: Analogous method for univariate polynomials.
        )r   rg   
shift_listr  s     ra   r	  zPoly.shift_list(  s"    $ uuQUU%%a())rd   c                 B   |j                  |      \  }}| j                  |      \  }}|j                  |      \  }}t        |j                  d      r1|j                  j                  |j                  |j                        }nt	        |d      |j                  |      S )a3  
        Efficiently evaluate the functional transformation ``q**n * f(p/q)``.


        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1, x), Poly(x - 1, x))
        Poly(4, x, domain='ZZ')

        	transform)r   r  rg   r  r4   r   )r\   r  rt  Pr  r   r_   s          ra   r  zPoly.transform<  s|     wwqz1wwqz1wwqz1155+&UU__QUUAEE2F';77uuV}rd   c                 "   | }|r0|j                   j                  j                  r|j                         }t	        |j                   d      r|j                   j                         }nt        |d      t        t        |j                  |            S )a  
        Computes the Sturm sequence of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**3 - 2*x**2 + x - 3, x).sturm()
        [Poly(x**3 - 2*x**2 + x - 3, x, domain='QQ'),
         Poly(3*x**2 - 4*x + 1, x, domain='QQ'),
         Poly(2/9*x + 25/9, x, domain='QQ'),
         Poly(-2079/4, x, domain='QQ')]

        sturm)
rg   r   r  r   r  r  r4   rt   r   r   r  s       ra   r  z
Poly.sturmV  sg    " AEEII%%

A155'"UU[[]F'733Cv&''rd   c                     t        | j                  d      r| j                  j                         }nt        | d      |D cg c]  \  }}| j	                  |      |f c}}S c c}}w )aI  
        Computes greatest factorial factorization of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> f = x**5 + 2*x**4 - x**3 - 2*x**2

        >>> Poly(f).gff_list()
        [(Poly(x, x, domain='ZZ'), 1), (Poly(x + 2, x, domain='ZZ'), 4)]

        gff_list)r  rg   r  r4   r   )r\   r_   r]   rR  s       ra   r  zPoly.gff_lists  sS      155*%UU^^%F':66*01$!Qq1111s   A$c                     t        | j                  d      r| j                  j                         }nt        | d      | j	                  |      S )a  
        Computes the product, ``Norm(f)``, of the conjugates of
        a polynomial ``f`` defined over a number field ``K``.

        Examples
        ========

        >>> from sympy import Poly, sqrt
        >>> from sympy.abc import x

        >>> a, b = sqrt(2), sqrt(3)

        A polynomial over a quadratic extension.
        Two conjugates x - a and x + a.

        >>> f = Poly(x - a, x, extension=a)
        >>> f.norm()
        Poly(x**2 - 2, x, domain='QQ')

        A polynomial over a quartic extension.
        Four conjugates x - a, x - a, x + a and x + a.

        >>> f = Poly(x - a, x, extension=(a, b))
        >>> f.norm()
        Poly(x**4 - 4*x**2 + 4, x, domain='QQ')

        norm)r  rg   r  r4   r   )r\   ru  s     ra   r  z	Poly.norm  s;    8 155&!

A'622uuQxrd   c                     t        | j                  d      r| j                  j                         \  }}}nt        | d      || j	                  |      | j	                  |      fS )ah  
        Computes square-free norm of ``f``.

        Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and
        ``r(x) = Norm(g(x))`` is a square-free polynomial over ``K``,
        where ``a`` is the algebraic extension of the ground domain.

        Examples
        ========

        >>> from sympy import Poly, sqrt
        >>> from sympy.abc import x

        >>> s, f, r = Poly(x**2 + 1, x, extension=[sqrt(3)]).sqf_norm()

        >>> s
        [1]
        >>> f
        Poly(x**2 - 2*sqrt(3)*x + 4, x, domain='QQ<sqrt(3)>')
        >>> r
        Poly(x**4 - 4*x**2 + 16, x, domain='QQ')

        sqf_norm)r  rg   r  r4   r   )r\   r  r]   ru  s       ra   r  zPoly.sqf_norm  sR    0 155*%eenn&GAq!':66!%%(AEE!H$$rd   c                     t        | j                  d      r| j                  j                         }nt        | d      | j	                  |      S )z
        Computes square-free part of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**3 - 3*x - 2, x).sqf_part()
        Poly(x**2 - x - 2, x, domain='ZZ')

        sqf_part)r  rg   r  r4   r   r  s     ra   r  zPoly.sqf_part  r  rd   c                 &   t        | j                  d      r| j                  j                  |      \  }}nt        | d      | j                  j                  j                  |      |D cg c]  \  }}| j                  |      |f c}}fS c c}}w )a   
        Returns a list of square-free factors of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> f = 2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16

        >>> Poly(f).sqf_list()
        (2, [(Poly(x + 1, x, domain='ZZ'), 2),
             (Poly(x + 2, x, domain='ZZ'), 3)])

        >>> Poly(f).sqf_list(all=True)
        (2, [(Poly(1, x, domain='ZZ'), 1),
             (Poly(x + 1, x, domain='ZZ'), 2),
             (Poly(x + 2, x, domain='ZZ'), 3)])

        sqf_list)r  rg   r  r4   r   r   r   )r\   allr   factorsr]   rR  s         ra   r  zPoly.sqf_list  sq    , 155*%UU^^C0NE7':66uuyy!!%(W*MTQAEE!Ha=*MMM*Ms   +Bc                     t        | j                  d      r| j                  j                  |      }nt        | d      |D cg c]  \  }}| j	                  |      |f c}}S c c}}w )a  
        Returns a list of square-free factors of ``f``.

        Examples
        ========

        >>> from sympy import Poly, expand
        >>> from sympy.abc import x

        >>> f = expand(2*(x + 1)**3*x**4)
        >>> f
        2*x**7 + 6*x**6 + 6*x**5 + 2*x**4

        >>> Poly(f).sqf_list_include()
        [(Poly(2, x, domain='ZZ'), 1),
         (Poly(x + 1, x, domain='ZZ'), 3),
         (Poly(x, x, domain='ZZ'), 4)]

        >>> Poly(f).sqf_list_include(all=True)
        [(Poly(2, x, domain='ZZ'), 1),
         (Poly(1, x, domain='ZZ'), 2),
         (Poly(x + 1, x, domain='ZZ'), 3),
         (Poly(x, x, domain='ZZ'), 4)]

        sqf_list_include)r  rg   r  r4   r   )r\   r  r  r]   rR  s        ra   r  zPoly.sqf_list_include  sY    4 155,-ee,,S1G'+=>>*12$!Qq1222s   A%c                    t        | j                  d      r	 | j                  j                         \  }}nt        | d      | j                  j                  j                  |      |D cg c]  \  }}| j                  |      |f c}}fS # t        $ r? | j	                         dk(  r| j                         g fcY S t        j                  | dfgfcY S w xY wc c}}w )a~  
        Returns a list of irreducible factors of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y

        >>> Poly(f).factor_list()
        (2, [(Poly(x + y, x, y, domain='ZZ'), 1),
             (Poly(x**2 + 1, x, y, domain='ZZ'), 2)])

        factor_listr   r   )r  rg   r  r5   r  rZ   r   r  r4   r   r   r   )r\   r   r  r]   rR  s        ra   r  zPoly.factor_list  s    " 155-(+!"!2!2!4w (=99uuyy!!%(W*MTQAEE!Ha=*MMM  +88:?99;?*55Aq6(?*	+ +Ns   B +C.C=CCc                     t        | j                  d      r	 | j                  j                         }nt	        | d      |D cg c]  \  }}| j                  |      |f c}}S # t        $ r | dfgcY S w xY wc c}}w )a  
        Returns a list of irreducible factors of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y

        >>> Poly(f).factor_list_include()
        [(Poly(2*x + 2*y, x, y, domain='ZZ'), 1),
         (Poly(x**2 + 1, x, y, domain='ZZ'), 2)]

        factor_list_includer   )r  rg   r   r5   r4   r   )r\   r  r]   rR  s       ra   r   zPoly.factor_list_include=  s{    " 155/0 %%335 (+@AA*12$!Qq122   Ax 
 3s   A% A9%A65A6c                 h   |%t        j                  |      }|dk  rt        d      |t        j                  |      }|t        j                  |      }t        | j                  d      r"| j                  j                  ||||||      }nt        | d      |rLd }|st        t        ||            S d }	|\  }
}t        t        ||
            t        t        |	|            fS d }|st        t        ||            S d }	|\  }
}t        t        ||
            t        t        |	|            fS )	a  
        Compute isolating intervals for roots of ``f``.

        For real roots the Vincent-Akritas-Strzebonski (VAS) continued fractions method is used.

        References
        ==========
        .. [#] Alkiviadis G. Akritas and Adam W. Strzebonski: A Comparative Study of Two Real Root
            Isolation Methods . Nonlinear Analysis: Modelling and Control, Vol. 10, No. 4, 297-304, 2005.
        .. [#] Alkiviadis G. Akritas, Adam W. Strzebonski and Panagiotis S. Vigklas: Improving the
            Performance of the Continued Fractions Method Using new Bounds of Positive Roots. Nonlinear
            Analysis: Modelling and Control, Vol. 13, No. 3, 265-279, 2008.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 - 3, x).intervals()
        [((-2, -1), 1), ((1, 2), 1)]
        >>> Poly(x**2 - 3, x).intervals(eps=1e-2)
        [((-26/15, -19/11), 1), ((19/11, 26/15), 1)]

        r   !'eps' must be a positive rational	intervalsr  epsinfsupfastsqfc                 `    | \  }}t        j                  |      t        j                  |      fS r   r*   r   )intervalr  r  s      ra   _realzPoly.intervals.<locals>._real  s&    1AA77rd   c                     | \  \  }}\  }}t        j                  |      t        t        j                  |      z  z   t        j                  |      t        t        j                  |      z  z   fS r   r*   r   r   )	rectangleuvr  r  s        ra   _complexz Poly.intervals.<locals>._complex  sW    !*AAA2;;q>)99A2;;q>)99; ;rd   c                 j    | \  \  }}}t        j                  |      t        j                  |      f|fS r   r+  )r,  r  r  rR  s       ra   r-  zPoly.intervals.<locals>._real  s/    $	AQQ8!<<rd   c                     | \  \  \  }}\  }}}t        j                  |      t        t        j                  |      z  z   t        j                  |      t        t        j                  |      z  z   f|fS r   r/  )r0  r1  r2  r  r  rR  s         ra   r3  z Poly.intervals.<locals>._complex  sg    &/# !Q!Q!Q!BKKN*::Q!BKKN*::<=>@ @rd   )	r*   r   r  r  rg   r#  r4   rt   r   )r\   r  r%  r&  r'  r(  r)  r_   r-  r3  	real_partcomplex_parts               ra   r#  zPoly.intervalsX  s3   4 ?**S/Cax !DEE?**S/C?**S/C155+&UU__Scs3 % HF (;778 Cv.//;
 '-#I|E9-.S<5P0QQQ= Cv.//@
 '-#I|E9-.S<5P0QQQrd   c                    |r| j                   st        d      t        j                  |      t        j                  |      }}|%t        j                  |      }|dk  rt	        d      |t        |      }n|d}t        | j                  d      r$| j                  j                  |||||      \  }}nt        | d      t        j                  |      t        j                  |      fS )a  
        Refine an isolating interval of a root to the given precision.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 - 3, x).refine_root(1, 2, eps=1e-2)
        (19/11, 26/15)

        z&only square-free polynomials supportedr   r"  r   refine_root)r%  stepsr(  )is_sqfr9   r*   r   r  r(  r  rg   r9  r4   r   )	r\   r  r  r%  r:  r(  	check_sqfr   Ts	            ra   r9  zPoly.refine_root  s     QXX!"JKKzz!}bjjm1?**S/Cax !DEEJE[E155-(55$$Qs%d$KDAq'=99{{1~r{{1~--rd   c                 d   d\  }}|rt        |      }|t        j                  u rd}nR|j                         \  }}|st	        j
                  |      }n't        t        t        j
                  ||f            d}}|rt        |      }|t        j                  u rd}nR|j                         \  }}|st	        j
                  |      }n't        t        t        j
                  ||f            d}}|rL|rJt        | j                  d      r(| j                  j                  ||      }t        |      S t        | d      |r||t        j                  f}|r||t        j                  f}t        | j                  d      r(| j                  j                  ||      }t        |      S t        | d      )a<  
        Return the number of roots of ``f`` in ``[inf, sup]`` interval.

        Examples
        ========

        >>> from sympy import Poly, I
        >>> from sympy.abc import x

        >>> Poly(x**4 - 4, x).count_roots(-3, 3)
        2
        >>> Poly(x**4 - 4, x).count_roots(0, 1 + 3*I)
        1

        TTNFcount_real_rootsr&  r'  count_complex_roots)r"   r   r  as_real_imagr*   r   rt   r   Infinityr  rg   r@  r4   r   rB  r   )r\   r&  r'  inf_realsup_realreimcounts           ra   count_rootszPoly.count_roots  s     ((?#,Ca((())+B**S/C$(RZZ"b)B$CUC?#,Cajj ))+B**S/C$(RZZ"b)B$CUCquu01..3C.@ u~ ,A/ABBCOBGGnCOBGGnquu3411cs1C u~ ,A/DEErd   c                 Z    t         j                  j                  j                  | ||      S )a  
        Get an indexed root of a polynomial.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> f = Poly(2*x**3 - 7*x**2 + 4*x + 4)

        >>> f.root(0)
        -1/2
        >>> f.root(1)
        2
        >>> f.root(2)
        2
        >>> f.root(3)
        Traceback (most recent call last):
        ...
        IndexError: root index out of [-3, 2] range, got 3

        >>> Poly(x**5 + x + 1).root(0)
        CRootOf(x**3 - x**2 + 1, 0)

        radicals)sympypolysrootoftoolsrootof)r\   r   rM  s      ra   rootz	Poly.root  s&    6 {{&&--a-JJrd   c                     t         j                  j                  j                  j	                  | |      }|r|S t        |d      S )a  
        Return a list of real roots with multiplicities.

        See :func:`real_roots` for more explanation.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(2*x**3 - 7*x**2 + 4*x + 4).real_roots()
        [-1/2, 2, 2]
        >>> Poly(x**3 + x + 1).real_roots()
        [CRootOf(x**3 + x + 1, 0)]
        rL  Fmultiple)rN  rO  rP  CRootOf
real_rootsrG   )r\   rU  rM  realss       ra   rW  zPoly.real_roots%  s>    " ''//::1x:PL//rd   c                     t         j                  j                  j                  j	                  | |      }|r|S t        |d      S )a  
        Return a list of real and complex roots with multiplicities.

        See :func:`all_roots` for more explanation.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(2*x**3 - 7*x**2 + 4*x + 4).all_roots()
        [-1/2, 2, 2]
        >>> Poly(x**3 + x + 1).all_roots()
        [CRootOf(x**3 + x + 1, 0),
         CRootOf(x**3 + x + 1, 1),
         CRootOf(x**3 + x + 1, 2)]

        rL  FrT  )rN  rO  rP  rV  	all_rootsrG   )r\   rU  rM  rootss       ra   rZ  zPoly.all_roots=  s>    ( ''//99!h9OL//rd   c                   
 | j                   rt        d| z        | j                         dk  rg S | j                  j                  t
        u r'| j                         D cg c]  }t        |       }}n| j                  j                  t        u rY| j                         D cg c]  }|j                   }}t        | }| j                         D cg c]  }t        ||z         }}n[| j                         D cg c]"  }|j                  |      j                         $ }}	 |D cg c]  }t        j                  |  }}t        j"                  j$                  }|t        j"                  _        ddlm
 	 t        j*                  |||d| j                         dz        }	t-        t/        t0        t3        |	
fd	
                  }	|t        j"                  _        |	S c c}w c c}w c c}w c c}w c c}w # t        $ r# t!        d| j                  j                  z        w xY w# t4        $ ru 	 t        j*                  |||d| j                         dz        }	t-        t/        t0        t3        |	
fd
                  }	n# t4        $ r t5        d|d|      w xY wY w xY w# |t        j"                  _        w xY w)a  
        Compute numerical approximations of roots of ``f``.

        Parameters
        ==========

        n ... the number of digits to calculate
        maxsteps ... the maximum number of iterations to do

        If the accuracy `n` cannot be reached in `maxsteps`, it will raise an
        exception. You need to rerun with higher maxsteps.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 - 3).nroots(n=15)
        [-1.73205080756888, 1.73205080756888]
        >>> Poly(x**2 - 3).nroots(n=30)
        [-1.73205080756887729352744634151, 1.73205080756887729352744634151]

        z$Cannot compute numerical roots of %sr   )r*  z!Numerical domain expected, got %s)signF
   )maxstepscleanuperror	extraprecc                     | j                   rdnd| j                  t        | j                          | j                         fS Nr   r   imagrealrc  ru  r]  s    ra   <lambda>zPoly.nroots.<locals>.<lambda>  s1    !&&QaQVVVZ[\[a[aVb,c rd   key   c                     | j                   rdnd| j                  t        | j                          | j                         fS rd  re  rh  s    ra   ri  zPoly.nroots.<locals>.<lambda>  s4    aff!QVVSQRQWQW[Z^_`_e_eZf0g rd   z$convergence to root failed; try n < z or maxsteps > )is_multivariater:   r  rg   r   r+   r1  r(  r*   rt  r   r   rC  mpmathmpcr  r5   mpdps$sympy.functions.elementary.complexesr]  	polyrootsrt   r   r"   sortedrM   )r\   r*  r_  r`  r   r   denomsfacrr  r[  r]  s             @ra   nrootszPoly.nrootsX  sm   2 -6:< < 88:?I
 5599?./lln=Uc%j=F=UUYY"_+,<<>:%egg:F:-C23,,.Ac%)nAFA "#1 kkAk&335 1F 1#:@A&**e,AA
 iimm		=	  $$Vh#5AHHJrMKE
 Wu"cdf gE  FIIMU >:A1 B #!"E		#" # ##$  
	"	"(((#5AHHJrMKS5&ghj k  "#x!" "" 
	"  FIIMst   G#"G(G-;'G2%G< )G7G< :AH+ 7G< <,H(+	J)5AJJ)J##J)&J, (J))J, ,Kc                     | j                   rt        d| z        i }| j                         d   D ].  \  }}|j                  s|j	                         \  }}||| |z  <   0 |S )a  
        Compute roots of ``f`` by factorization in the ground domain.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**6 - 4*x**4 + 4*x**3 - x**2).ground_roots()
        {0: 2, 1: 2}

        z!Cannot compute ground roots of %sr   )rn  r:   r  	is_linearr1  )r\   r[  factorrR  r  r  s         ra   ground_rootszPoly.ground_roots  sx     -3a79 9 + 	 IFA((*1qbd	 
 rd   c                 R   | j                   rt        d      t        |      }|j                  r|dk\  rt	        |      }nt        d|z        | j                  }t        d      }| j                  | j                  j                  ||z  |z
  ||            }|j                  ||      S )af  
        Construct a polynomial with n-th powers of roots of ``f``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> f = Poly(x**4 - x**2 + 1)

        >>> f.nth_power_roots_poly(2)
        Poly(x**4 - 2*x**3 + 3*x**2 - 2*x + 1, x, domain='ZZ')
        >>> f.nth_power_roots_poly(3)
        Poly(x**4 + 2*x**2 + 1, x, domain='ZZ')
        >>> f.nth_power_roots_poly(4)
        Poly(x**4 + 2*x**3 + 3*x**2 + 2*x + 1, x, domain='ZZ')
        >>> f.nth_power_roots_poly(12)
        Poly(x**4 - 4*x**3 + 6*x**2 - 4*x + 1, x, domain='ZZ')

        zmust be a univariate polynomialr   z&'n' must an integer and n >= 1, got %sr  )rn  r:   r"   
is_Integerr(  r  r   r    r  r   rU   r   )r\   r*  r  r  r  ru  s         ra   nth_power_roots_polyzPoly.nth_power_roots_poly  s    , -13 3 AJ<<AFAAEIJJEE#JKK--adQh1=>yyArd   c                    | j                   rt        d      | j                  j                         }| j                  j                         j                  |      }|dz  }t        d|z  di       \  }}}}t        |      }|dz  |dz  z   fd}	 |	|       |	|      }}
|
j                  |j                  z
  dz  |
j                  |j                  z
  dz  z   |k  S )a  
        Decide whether two roots of this polynomial are equal.

        Examples
        ========

        >>> from sympy import Poly, cyclotomic_poly, exp, I, pi
        >>> f = Poly(cyclotomic_poly(5))
        >>> r0 = exp(2*I*pi/5)
        >>> indices = [i for i, r in enumerate(f.all_roots()) if f.same_root(r, r0)]
        >>> print(indices)
        [3]

        Raises
        ======

        DomainError
            If the domain of the polynomial is not :ref:`ZZ`, :ref:`QQ`,
            :ref:`RR`, or :ref:`CC`.
        MultivariatePolynomialError
            If the polynomial is not univariate.
        PolynomialError
            If the polynomial is of degree < 2.

        zMust be a univariate polynomial	   r      c                 0    t        t        |             S )Nr  )r   r   )r  r)  s    ra   ri  z Poly.same_root.<locals>.<lambda>  s    ~&?Q&GH rd   )rn  r:   rg   mignotte_sep_bound_squaredrP   	get_fieldr   r   r   rg  rf  )r\   r  r  dom_delta_sqdelta_sqeps_sqru  r   r*  evABr)  s               @ra   	same_rootzPoly.same_root  s    4 -13 3 uu77988%%'00> A1V8Q+
1aAJ!VAH !ube1!#qvv&::VCCrd   c                 f   | j                  |      \  }}}}t        |d      r|j                  ||      }nt        | d      |sY|j                  r|j                         }|\  }}	}
}|j                  |      }|j                  |	      }	||	z   ||
       ||      fS t        t        ||            S )a  
        Cancel common factors in a rational function ``f/g``.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x))
        (1, Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ'))

        >>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x), include=True)
        (Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ'))

        cancel)include)	r   r  r  r4   r  r  r   r7  r   )r\   r]   r  r   r   r   r   r_   cpcqr  rt  s               ra   r  zPoly.cancel  s    " !S!Q1hXXaX1F'844!!lln!LBAqb!Bb!Bb5#a&#a&((S&)**rd   c                 r   | j                   r| j                  t        t        fvrt	        d      | j
                  r%| j                  t        k(  r| t        j                  fS | j                         }|j                         \  }}|j                  t        |j                        |      j                         |fS )aQ  
        Turn any univariate polynomial over :ref:`QQ` or :ref:`ZZ` into a monic
        polynomial over :ref:`ZZ`, by scaling the roots as necessary.

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

        This operation can be performed whether or not *f* is irreducible; when
        it is, this can be understood as determining an algebraic integer
        generating the same field as a root of *f*.

        Examples
        ========

        >>> from sympy import Poly, S
        >>> from sympy.abc import x
        >>> f = Poly(x**2/2 + S(1)/4 * x + S(1)/8, x, domain='QQ')
        >>> f.make_monic_over_integers_by_scaling_roots()
        (Poly(x**2 + 2*x + 4, x, domain='ZZ'), 4)

        Returns
        =======

        Pair ``(g, c)``
            g is the polynomial

            c is the integer by which the roots had to be scaled

        z,Polynomial must be univariate over ZZ or QQ.)r   rP   r+   r*   r  is_monicr   r  r  r  rT   r   r  )r\   fmr   r   s       ra   )make_monic_over_integers_by_scaling_rootsz.Poly.make_monic_over_integers_by_scaling_rootsC  s    < !((2r(":KLL::!((b.bff9B??$DAq<<RVVa088:A==rd   c                    ddl m}m}m}m} | j
                  r$| j                  r| j                  t        t        fvrt        d      ||||d}t        |j                               }	| j                         }
|
|	kD  rt        d|	 d      |
dk  rt        d      |
dk(  rdd	lm} |j                   d
}}n>|
dk(  rddlm} |j$                  d}}n$| j'                         \  }} ||
   |||      \  }}|r|n|j)                         }||fS )a  
        Compute the Galois group of this polynomial.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x
        >>> f = Poly(x**4 - 2)
        >>> G, _ = f.galois_group(by_name=True)
        >>> print(G)
        S4TransitiveSubgroups.D4

        See Also
        ========

        sympy.polys.numberfields.galoisgroups.galois_group

        r   )_galois_group_degree_3_galois_group_degree_4_lookup(_galois_group_degree_5_lookup_ext_factor_galois_group_degree_6_lookupz<Polynomial must be irreducible and univariate over ZZ or QQ.)            zOnly polynomials up to degree z are supported.r   z(Constant polynomial has no Galois group.)S1TransitiveSubgroupsTr  )S2TransitiveSubgroupsF)	max_tries	randomize)%sympy.polys.numberfields.galoisgroupsr  r  r  r  r   is_irreduciblerP   r+   r*   r  maxkeysr  sympy.combinatorics.galoisr  S1r  S2r  get_perm_group)r\   by_namer  r  r  r  r  r  ggmax_supportedr*  r  namealtr  r]   r   r   s                     ra   galois_groupzPoly.galois_groupj  s   (	
 	

 ##xxBx'[\\%,7,	
 BGGIHHJ}=m_O\]]UGHH!VH-00$#D!VH-00%#D>>@DAq1a9	JID#D!4!4!6#vrd   c                 .    | j                   j                  S )a  
        Returns ``True`` if ``f`` is a zero polynomial.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(0, x).is_zero
        True
        >>> Poly(1, x).is_zero
        False

        )rg   is_zeror   s    ra   r  zPoly.is_zero  s    " uu}}rd   c                 .    | j                   j                  S )a  
        Returns ``True`` if ``f`` is a unit polynomial.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(0, x).is_one
        False
        >>> Poly(1, x).is_one
        True

        )rg   is_oner   s    ra   r  zPoly.is_one      " uu||rd   c                 .    | j                   j                  S )a   
        Returns ``True`` if ``f`` is a square-free polynomial.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 - 2*x + 1, x).is_sqf
        False
        >>> Poly(x**2 - 1, x).is_sqf
        True

        )rg   r;  r   s    ra   r;  zPoly.is_sqf  r  rd   c                 .    | j                   j                  S )a   
        Returns ``True`` if the leading coefficient of ``f`` is one.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x + 2, x).is_monic
        True
        >>> Poly(2*x + 2, x).is_monic
        False

        )rg   r  r   s    ra   r  zPoly.is_monic  s    " uu~~rd   c                 .    | j                   j                  S )a;  
        Returns ``True`` if GCD of the coefficients of ``f`` is one.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(2*x**2 + 6*x + 12, x).is_primitive
        False
        >>> Poly(x**2 + 3*x + 6, x).is_primitive
        True

        )rg   is_primitiver   s    ra   r  zPoly.is_primitive      " uu!!!rd   c                 .    | j                   j                  S )aJ  
        Returns ``True`` if ``f`` is an element of the ground domain.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x, x).is_ground
        False
        >>> Poly(2, x).is_ground
        True
        >>> Poly(y, x).is_ground
        True

        )rg   	is_groundr   s    ra   r  zPoly.is_ground  s    & uurd   c                 .    | j                   j                  S )a,  
        Returns ``True`` if ``f`` is linear in all its variables.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x + y + 2, x, y).is_linear
        True
        >>> Poly(x*y + 2, x, y).is_linear
        False

        )rg   rz  r   s    ra   rz  zPoly.is_linear  s    " uurd   c                 .    | j                   j                  S )a6  
        Returns ``True`` if ``f`` is quadratic in all its variables.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x*y + 2, x, y).is_quadratic
        True
        >>> Poly(x*y**2 + 2, x, y).is_quadratic
        False

        )rg   is_quadraticr   s    ra   r  zPoly.is_quadratic'  r  rd   c                 .    | j                   j                  S )a%  
        Returns ``True`` if ``f`` is zero or has only one term.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(3*x**2, x).is_monomial
        True
        >>> Poly(3*x**2 + 1, x).is_monomial
        False

        )rg   is_monomialr   s    ra   r  zPoly.is_monomial:  s    " uu   rd   c                 .    | j                   j                  S )aZ  
        Returns ``True`` if ``f`` is a homogeneous polynomial.

        A homogeneous polynomial is a polynomial whose all monomials with
        non-zero coefficients have the same total degree. If you want not
        only to check if a polynomial is homogeneous but also compute its
        homogeneous order, then use :func:`Poly.homogeneous_order`.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x**2 + x*y, x, y).is_homogeneous
        True
        >>> Poly(x**3 + x*y, x, y).is_homogeneous
        False

        )rg   is_homogeneousr   s    ra   r  zPoly.is_homogeneousM  s    , uu###rd   c                 .    | j                   j                  S )aG  
        Returns ``True`` if ``f`` has no factors over its domain.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> Poly(x**2 + x + 1, x, modulus=2).is_irreducible
        True
        >>> Poly(x**2 + 1, x, modulus=2).is_irreducible
        False

        )rg   r  r   s    ra   r  zPoly.is_irreduciblee  s    " uu###rd   c                 2    t        | j                        dk(  S )a  
        Returns ``True`` if ``f`` is a univariate polynomial.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x**2 + x + 1, x).is_univariate
        True
        >>> Poly(x*y**2 + x*y + 1, x, y).is_univariate
        False
        >>> Poly(x*y**2 + x*y + 1, x).is_univariate
        True
        >>> Poly(x**2 + x + 1, x, y).is_univariate
        False

        r   r   rV   r   s    ra   r   zPoly.is_univariatex      * 166{ard   c                 2    t        | j                        dk7  S )a  
        Returns ``True`` if ``f`` is a multivariate polynomial.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x, y

        >>> Poly(x**2 + x + 1, x).is_multivariate
        False
        >>> Poly(x*y**2 + x*y + 1, x, y).is_multivariate
        True
        >>> Poly(x*y**2 + x*y + 1, x).is_multivariate
        False
        >>> Poly(x**2 + x + 1, x, y).is_multivariate
        True

        r   r  r   s    ra   rn  zPoly.is_multivariate  r  rd   c                 .    | j                   j                  S )a  
        Returns ``True`` if ``f`` is a cyclotomic polnomial.

        Examples
        ========

        >>> from sympy import Poly
        >>> from sympy.abc import x

        >>> f = x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1

        >>> Poly(f).is_cyclotomic
        False

        >>> g = x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1

        >>> Poly(g).is_cyclotomic
        True

        )rg   is_cyclotomicr   s    ra   r  zPoly.is_cyclotomic  s    , uu"""rd   c                 "    | j                         S r   )rc  r   s    ra   __abs__zPoly.__abs__      uuwrd   c                 "    | j                         S r   )re  r   s    ra   __neg__zPoly.__neg__  r  rd   c                 $    | j                  |      S r   r  r\   r]   s     ra   __add__zPoly.__add__      uuQxrd   c                 $    |j                  |       S r   r  r  s     ra   __radd__zPoly.__radd__  r  rd   c                 $    | j                  |      S r   rk  r  s     ra   __sub__zPoly.__sub__  r  rd   c                 $    |j                  |       S r   r  r  s     ra   __rsub__zPoly.__rsub__  r  rd   c                 $    | j                  |      S r   r   r  s     ra   __mul__zPoly.__mul__  r  rd   c                 $    |j                  |       S r   r   r  s     ra   __rmul__zPoly.__rmul__  r  rd   r*  c                 R    |j                   r|dk\  r| j                  |      S t        S )Nr   )r~  rp  rX   )r\   r*  s     ra   __pow__zPoly.__pow__  s"    <<AF558O!!rd   c                 $    | j                  |      S r   r~  r  s     ra   
__divmod__zPoly.__divmod__  r  rd   c                 $    |j                  |       S r   r  r  s     ra   __rdivmod__zPoly.__rdivmod__  r  rd   c                 $    | j                  |      S r   r  r  s     ra   __mod__zPoly.__mod__  r  rd   c                 $    |j                  |       S r   r  r  s     ra   __rmod__zPoly.__rmod__  r  rd   c                 $    | j                  |      S r   r  r  s     ra   __floordiv__zPoly.__floordiv__  r  rd   c                 $    |j                  |       S r   r  r  s     ra   __rfloordiv__zPoly.__rfloordiv__  r  rd   r]   c                 D    | j                         |j                         z  S r   rZ   r  s     ra   __truediv__zPoly.__truediv__      yy{199;&&rd   c                 D    |j                         | j                         z  S r   r  r  s     ra   __rtruediv__zPoly.__rtruediv__  r  rd   otherc                 r   | |}}|j                   s-	 |j                  ||j                  |j                               }|j                  |j                  k7  ry|j                  j                  |j                  j                  k7  ry|j                  |j                  k(  S # t        t
        t        f$ r Y yw xY wNr$  F)	rv   r   rV   r   r9   r5   r6   rg   r   )r   r  r\   r]   s       ra   __eq__zPoly.__eq__  s    U1yyKK166!,,.KA 66QVV5599		!uu~ $[.A s   ,B B65B6c                     | |k(   S r   r  r  s     ra   __ne__zPoly.__ne__  s    6zrd   c                     | j                    S r   )r  r   s    ra   __bool__zPoly.__bool__  s    99}rd   c                 D    |s| |k(  S | j                  t        |            S r   )
_strict_eqr"   r\   r]   stricts      ra   eqzPoly.eq  s!    6M<<
++rd   c                 *    | j                  ||       S )Nr  )r  r  s      ra   nezPoly.ne"  s    44&4)))rd   c                     t        || j                        xrB | j                  |j                  k(  xr' | j                  j	                  |j                  d      S NTr  )rS   r   rV   rg   r  r  s     ra   r   zPoly._strict_eq%  s@    !Q[[)_aff.>_15588AEEZ^8C__rd   NNr   )FF)FTr   )r   FNT)FNNNFFNNFFr?  rl  2   T)F   F)r[   
__module____qualname____doc__	__slots__is_commutativerv   _op_priorityr}   classmethodr   propertyr   r{   r   r   r   r   rU   rr   rs   rw   rx   ro   r   r   r   r   rP   r   r   r   r   r   r   r   r   r   r   r   rj   r   r  r   r  r  r  r   r   r%  r'  r   r   r  r1  r3  r5  r8  r:  r  r?  rZ   rE  rG  rI  rL  rQ  rU  rW  r[  r]  r_  ra  rc  re  r  rk  r   rn  rp  rs  rw  ry  r{  r~  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r  _eval_derivativer   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r	  r  r  r  r  r  r  r  r  r  r   r#  r9  rJ  rR  rW  rZ  rx  r|  r  r  r  r  r  r  r  r;  r  r  r  rz  r  r  r  r  r   rn  r  r  r  rc   r  r  r  r  r  r  r   rX   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   __classcell__r   s   @ra   rT   rT   i   s   3j  INGL0>   E E ( (' ( (
 ( (
 ( (
 ( (
 A A& A A*  , ( (
 A A" 5 5<  :    ! !, O O N N O O83j+:0
)"J**%&!MF2N4"LH D***40 J,)(Q(C "(J #=J  2&)$=L4* *#$J(%T ****04*0>>>04.%N8>%N#J#J(T@(5<:&;* <D@2*0**1&#9J *D
14(5 .*."****%&N%N&8P$3L I'V,>&B> D&2#%J'*I#VI V*:...:**7*.(*%(*(4(:2.!F%>*N:3BN<36JRX#.J=~K:0006N`6&P1Df#+J%>N4l  $  $  $  $ " "$  (  $ " "$ ! !$ $ $. $ $$    ,    , # #.             ^$" %"             ^$' %' ^$' %' ( )" ^$ %,*`rd   rT   c                   b     e Zd ZdZd Z fdZed        Z ede	      d        Z
d Zd Z xZS )	PurePolyz)Class for representing pure polynomials. c                     | j                   fS )z$Allow SymPy to hash Poly instances. )rg   r   s    ra   r   zPurePoly._hashable_content-  s    {rd   c                      t         |          S r   r   r   s    ra   r   zPurePoly.__hash__1  r   rd   c                     | j                   S )aR  
        Free symbols of a polynomial.

        Examples
        ========

        >>> from sympy import PurePoly
        >>> from sympy.abc import x, y

        >>> PurePoly(x**2 + 1).free_symbols
        set()
        >>> PurePoly(x**2 + y).free_symbols
        set()
        >>> PurePoly(x**2 + y, x).free_symbols
        {y}

        )r   r   s    ra   r   zPurePoly.free_symbols4  s    & ***rd   r  c                    | |}}|j                   s-	 |j                  ||j                  |j                               }t        |j                        t        |j                        k7  ry|j                  j                  |j                  j                  k7  rg	 |j                  j                  j                  |j                  j                  |j                        }|j                  |      }|j                  |      }|j                  |j                  k(  S # t        t
        t        f$ r Y yw xY w# t        $ r Y yw xY wr  )rv   r   rV   r   r9   r5   r6   r   rg   r   r   r7   r   )r   r  r\   r]   r   s        ra   r  zPurePoly.__eq__I  s    U1yyKK166!,,.KA qvv;#aff+%5599		!eeiiooaeeii8 S!AS!Auu~ $[.A  % s$   ,D AD1 D.-D.1	D=<D=c                     t        || j                        xr' | j                  j                  |j                  d      S r  )rS   r   rg   r  r  s     ra   r   zPurePoly._strict_eqa  s-    !Q[[)JaeehhquuTh.JJrd   c                 t   t        |      }|j                  sk	 | j                  j                  | j                  | j                  | j                  j	                  | j                  j                  j                  |            fS t        | j                        t        |j                        k7  rt        d| d|      t        | j                  t              rt        |j                  t              st        d| d|      | j                  | j                  }| j                  j                  j                  |j                  j                  |      }| j                  j                  |      }|j                  j                  |      }||d ffd	}||||fS # t        $ r t        d| d|      w xY w)Nr   r   c                 p    |!|d | ||dz   d  z   }|s|j                  |       S  j                  | g| S r   r   r   s       ra   r   zPurePoly._unify.<locals>.per{  r   rd   )r"   rv   rg   r   r   r   r6   r7   r   rV   rS   r1   r   r   r   )r\   r]   rV   r   r   r   r   rz   s          @ra   r   zPurePoly._unifyd  sB   AJyyLuuyy!%%		!%%)):N:Nq:Q0RRR qvv;#aff+%#A$FGG155#&:aeeS+A#A$FGGkkvveeiiooaeeii.EEMM#EEMM#4 	' CA~5 " L'Q(JKKLs   A)F F7)r[   r  r  r  r   r   r  r   r   rX   r  r   r   r  r  s   @ra   r  r  )  sJ    3" + +( ( ).K rd   r  c                 F    t        j                  ||      }t        | |      S r   )rl   rm   _poly_from_expr)r   rV   r{   r|   s       ra   poly_from_exprr'    s#     

d
+C4%%rd   c                    | t        |       } }t        | t              st        |||       | j                  rU| j
                  j                  | |      }|j                  |_        |j                  |_        |j                  d|_	        ||fS |j                  r| j                         } t        | |      \  }}|j                  st        |||       t        t        t        |j                                      \  }}|j                  }|t        ||      \  |_        }nt        t!        |j"                  |            }t%        t        t        ||                  }t&        j)                  ||      }|j                  d|_	        ||fS )r   Tr   F)r"   rS   r   r<   rv   r   rw   rV   rP   rO  expandrC   rt   r   r   r(   r   r   rq   rT   rr   )r   r|   origrD  rg   r   r   rP   s           ra   r&  r&    sE   wt}$DdE" dD11	~~((s399[[
99CISy	{{}tS)HC88 dD11#tCIIK012NFFZZF~-f#>
Fc&++V45
tC'(
)C??3$D
yy	9rd   c                 F    t        j                  ||      }t        | |      S )(Construct polynomials from expressions. )rl   rm   _parallel_poly_from_expr)exprsrV   r{   r|   s       ra   parallel_poly_from_exprr/    s#     

d
+C#E3//rd   c           	      j   t        |       dk(  r| \  }}t        |t              rt        |t              r|j                  j	                  ||      }|j                  j	                  ||      }|j                  |      \  }}|j                  |_        |j                  |_        |j                  d|_        ||g|fS t        |       g } }g g }}d}t        |      D ]  \  }}	t        |	      }	t        |	t              rL|	j                  r|j                  |       n0|j                  |       |j                  r|	j                         }	nd}| j                  |	        |rt!        ||| d      |r|D ]  }| |   j#                         | |<    t%        | |      \  }
}|j                  st!        ||| d      ddlm} |j                  D ]  }t        ||      st+        d       g g }}g }g }|
D ]i  }t        t-        t        |j/                                      \  }}|j1                  |       |j                  |       |j                  t        |             k |j                  }|t3        ||      \  |_        }nt        t5        |j6                  |            }|D ]  }|j                  |d|        ||d } g }t-        ||      D ]J  \  }}t9        t        t-        ||                  }t        j;                  ||      }|j                  |       L |j                  t=        |      |_        ||fS )	r,  r  NTFr   	Piecewisez&Piecewise generators do not make senser   )r   rS   rT   r   rw   r   rV   rP   rO  rt   r   r"   r   rv   appendr)  r<   rZ   rD   $sympy.functions.elementary.piecewiser2  r9   r   r   extendr(   r   r   rq   rr   bool)r.  r|   r\   r]   origs_exprs_polysfailedr   r   repsr2  rR  coeffs_listlengthsr3  r1  rg   r   r   rP   rO  rD  s                          ra   r-  r-    s   
5zQ1a:a#6&&q#.A&&q#.A771:DAqvvCHCJyy  	q63;;5EFFFU# 4t}dE"||a a ::;;=DFT   eUD99 	*AQx'')E!H	* )4ID#88 eUD99>XX La#!"JKKL rKJJ $c4		#4566"&!s6{#$ ZZF~"2;C"H
K3v00+>? &+bq/*!!"o& Ej*5 4FF+,-sC(T
 yyL	#:rd   c                 .    t        |       } || vr|| |<   | S )z7Add a new ``(key, value)`` pair to arguments ``dict``. )rq   )r{   rk  rB  s      ra   _update_argsr?    s     :D
$S	Krd   c                     t        | d      } t        |d      j                  }| j                  r| }|j                         j                  }n.| j                  }|s |rt	        |       \  }}nt	        | |      \  }}|r"| rt
        j                  S t
        j                  S |sT| j                  r*|j                  vrt	        | j                               \  }}|j                  vrnt
        j                  S | j                  sRt        | j                        dkD  r:t        t        d| dt        t        | j                              d|d            j                  |      }t!        |t"              rt%        |      S t
        j                  S )a  
    Return the degree of ``f`` in the given variable.

    The degree of 0 is negative infinity.

    Examples
    ========

    >>> from sympy import degree
    >>> from sympy.abc import x, y

    >>> degree(x**2 + y*x + 1, gen=x)
    2
    >>> degree(x**2 + y*x + 1, gen=y)
    1
    >>> degree(0, x)
    -oo

    See also
    ========

    sympy.polys.polytools.Poly.total_degree
    degree_list
    Tr  r   zj
         A symbolic generator of interest is required for a multivariate
         expression like func = z, e.g. degree(func, gen = z)) instead of
         degree(func, gen = z).
        )r"   	is_Numberrv   rZ   r'  r   Zeror  rV   r   r   r  rI   nextr   r  rS   r(  r   )r\   r   
gen_is_Numr  isNumr   r_   s          ra   r  r  %  s8   6 	$AT*44Jyy		%%%a(1%a-1qvv2 2 2299AFF*!!))+.DAqaff66MYY3q~~.2
 $wq~~./	$6 7 8 	8
 XXc]F(576?M1;M;MMrd   c                    t        |       }|j                  r|j                         }|j                  rd}t        |      S | j                  r|xs | j                  }t        ||      j                         }t        |      S )a  
    Return the total_degree of ``f`` in the given variables.

    Examples
    ========
    >>> from sympy import total_degree, Poly
    >>> from sympy.abc import x, y

    >>> total_degree(1)
    0
    >>> total_degree(x + x*y)
    2
    >>> total_degree(x + x*y, x)
    1

    If the expression is a Poly and no variables are given
    then the generators of the Poly will be used:

    >>> p = Poly(x + x*y, y)
    >>> total_degree(p)
    1

    To deal with the underlying expression of the Poly, convert
    it to an Expr:

    >>> total_degree(p.as_expr())
    2

    This is done automatically if any variables are given:

    >>> total_degree(p, x)
    1

    See also
    ========
    degree
    r   )r"   rv   rZ   rA  rV   rT   r  r   )r\   rV   r  rvs       ra   r  r  `  sl    P 	
AyyIIK{{ 2;	 99>166D!T]'')2;rd   c                     t        j                  |dg       	 t        | g|i |\  }}|j                         }t        t        t        |            S # t        $ r}t	        dd|      d}~ww xY w)z
    Return a list of degrees of ``f`` in all variables.

    Examples
    ========

    >>> from sympy import degree_list
    >>> from sympy.abc import x, y

    >>> degree_list(x**2 + y*x + 1)
    (2, 1)

    rO  r  r   N)	rl   allowed_flagsr'  r<   r=   r  r7  r   r   )r\   rV   r{   r   r|   r|  degreess          ra   r  r    ss     $	*71D1D13 mmoGWg&''  7q#667s   A 	A/A**A/c                     t        j                  |dg       	 t        | g|i |\  }}|j                  |j                        S # t        $ r}t	        dd|      d}~ww xY w)z
    Return the leading coefficient of ``f``.

    Examples
    ========

    >>> from sympy import LC
    >>> from sympy.abc import x, y

    >>> LC(4*x**2 + 2*x*y**2 + x*y + 3*y)
    4

    rO  r  r   Nr,  )rl   rI  r'  r<   r=   r  ri   r\   rV   r{   r   r|   r|  s         ra   r  r    sk     $	*.1D1D13 44cii4    .a--.s   A 	A"AA"c                     t        j                  |dg       	 t        | g|i |\  }}|j                  |j                        }|j                         S # t        $ r}t	        dd|      d}~ww xY w)z
    Return the leading monomial of ``f``.

    Examples
    ========

    >>> from sympy import LM
    >>> from sympy.abc import x, y

    >>> LM(4*x**2 + 2*x*y**2 + x*y + 3*y)
    x**2

    rO  r  r   Nr,  )rl   rI  r'  r<   r=   r  ri   rZ   )r\   rV   r{   r   r|   r|  r   s          ra   r  r    sv     $	*.1D1D13 DDsyyD!E==?	  .a--.s   A 	A2 A--A2c                     t        j                  |dg       	 t        | g|i |\  }}|j                  |j                        \  }}||j                         z  S # t        $ r}t	        dd|      d}~ww xY w)z
    Return the leading term of ``f``.

    Examples
    ========

    >>> from sympy import LT
    >>> from sympy.abc import x, y

    >>> LT(4*x**2 + 2*x*y**2 + x*y + 3*y)
    4*x**2

    rO  r  r   Nr,  )rl   rI  r'  r<   r=   r  ri   rZ   )r\   rV   r{   r   r|   r|  r   r   s           ra   r  r    s     $	*.1D1D13 44cii4(LE5  	  .a--.s   A 	A8&A33A8c                 $   t        j                  |dg       	 t        | |fg|i |\  \  }}}|j                  |      \  }}	|j                  s |j                         |	j                         fS ||	fS # t        $ r}t	        dd|      d}~ww xY w)z
    Compute polynomial pseudo-division of ``f`` and ``g``.

    Examples
    ========

    >>> from sympy import pdiv
    >>> from sympy.abc import x

    >>> pdiv(x**2 + 1, 2*x - 4)
    (2*x + 4, 20)

    rO  rs  r  N)rl   rI  r/  r<   r=   rs  rO  rZ   
r\   r]   rV   r{   r   r   r|   r|  rt  ru  s
             ra   rs  rs    s     $	*0-q!fDtDtDA 66!9DAq99yy{AIIK''!t  03//0s   A4 4	B=B

Bc                     t        j                  |dg       	 t        | |fg|i |\  \  }}}|j                  |      }|j                  s|j                         S |S # t        $ r}t	        dd|      d}~ww xY w)z
    Compute polynomial pseudo-remainder of ``f`` and ``g``.

    Examples
    ========

    >>> from sympy import prem
    >>> from sympy.abc import x

    >>> prem(x**2 + 1, 2*x - 4)
    20

    rO  rw  r  N)rl   rI  r/  r<   r=   rw  rO  rZ   	r\   r]   rV   r{   r   r   r|   r|  ru  s	            ra   rw  rw    s     $	*0-q!fDtDtDA 	
q	A99yy{  03//0   A 	A:(A55A:c                 .   t        j                  |dg       	 t        | |fg|i |\  \  }}}	 |j                  |      }|j                  s|j                         S |S # t        $ r}t	        dd|      d}~ww xY w# t        $ r t        | |      w xY w)z
    Compute polynomial pseudo-quotient of ``f`` and ``g``.

    Examples
    ========

    >>> from sympy import pquo
    >>> from sympy.abc import x

    >>> pquo(x**2 + 1, 2*x - 4)
    2*x + 4
    >>> pquo(x**2 - 1, 2*x - 1)
    2*x + 1

    rO  ry  r  N)	rl   rI  r/  r<   r=   ry  r;   rO  rZ   	r\   r]   rV   r{   r   r   r|   r|  rt  s	            ra   ry  ry  9  s    " $	*0-q!fDtDtDA(FF1I 99yy{  03//0
  (!!Q''(s"   A  A>  	A;)A66A;>Bc                     t        j                  |dg       	 t        | |fg|i |\  \  }}}|j                  |      }|j                  s|j                         S |S # t        $ r}t	        dd|      d}~ww xY w)a_  
    Compute polynomial exact pseudo-quotient of ``f`` and ``g``.

    Examples
    ========

    >>> from sympy import pexquo
    >>> from sympy.abc import x

    >>> pexquo(x**2 - 1, 2*x - 2)
    2*x + 2

    >>> pexquo(x**2 + 1, 2*x - 4)
    Traceback (most recent call last):
    ...
    ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1

    rO  r{  r  N)rl   rI  r/  r<   r=   r{  rO  rZ   rU  s	            ra   r{  r{  \  s    ( $	*2-q!fDtDtDA 	
A99yy{  2!S112rS  c                 >   t        j                  |ddg       	 t        | |fg|i |\  \  }}}|j                  ||j                        \  }}	|j                  s |j                         |	j                         fS ||	fS # t        $ r}t	        dd|      d}~ww xY w)a  
    Compute polynomial division of ``f`` and ``g``.

    Examples
    ========

    >>> from sympy import div, ZZ, QQ
    >>> from sympy.abc import x

    >>> div(x**2 + 1, 2*x - 4, domain=ZZ)
    (0, x**2 + 1)
    >>> div(x**2 + 1, 2*x - 4, domain=QQ)
    (x/2 + 1, 5)

    r  rO  r~  r  Nr  )	rl   rI  r/  r<   r=   r~  r  rO  rZ   rP  s
             ra   r~  r~    s    " $ 12/-q!fDtDtDA 555"DAq99yy{AIIK''!t  /q#../s   B 	B
BBc                    t        j                  |ddg       	 t        | |fg|i |\  \  }}}|j                  ||j                        }|j                  s|j                         S |S # t        $ r}t	        dd|      d}~ww xY w)a  
    Compute polynomial remainder of ``f`` and ``g``.

    Examples
    ========

    >>> from sympy import rem, ZZ, QQ
    >>> from sympy.abc import x

    >>> rem(x**2 + 1, 2*x - 4, domain=ZZ)
    x**2 + 1
    >>> rem(x**2 + 1, 2*x - 4, domain=QQ)
    5

    r  rO  r  r  NrX  )	rl   rI  r/  r<   r=   r  r  rO  rZ   rR  s	            ra   r  r        " $ 12/-q!fDtDtDA 	
achhA99yy{  /q#../   A, ,	B5BBc                    t        j                  |ddg       	 t        | |fg|i |\  \  }}}|j                  ||j                        }|j                  s|j                         S |S # t        $ r}t	        dd|      d}~ww xY w)z
    Compute polynomial quotient of ``f`` and ``g``.

    Examples
    ========

    >>> from sympy import quo
    >>> from sympy.abc import x

    >>> quo(x**2 + 1, 2*x - 4)
    x/2 + 1
    >>> quo(x**2 - 1, x - 1)
    x + 1

    r  rO  r  r  NrX  )	rl   rI  r/  r<   r=   r  r  rO  rZ   rU  s	            ra   r  r    rZ  r[  c                    t        j                  |ddg       	 t        | |fg|i |\  \  }}}|j                  ||j                        }|j                  s|j                         S |S # t        $ r}t	        dd|      d}~ww xY w)aQ  
    Compute polynomial exact quotient of ``f`` and ``g``.

    Examples
    ========

    >>> from sympy import exquo
    >>> from sympy.abc import x

    >>> exquo(x**2 - 1, x - 1)
    x + 1

    >>> exquo(x**2 + 1, 2*x - 4)
    Traceback (most recent call last):
    ...
    ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1

    r  rO  r  r  NrX  )	rl   rI  r/  r<   r=   r  r  rO  rZ   rU  s	            ra   r  r    s    ( $ 121-q!fDtDtDA 	
!A99yy{  1C001r[  c                    t        j                  |ddg       	 t        | |fg|i |\  \  }}}|j                  ||j                        \  }}|j                  s |j                         |j                         fS ||fS # t        $ rw}t	        |j
                        \  }\  }	}
	 |j                  |	|
      \  }}|j                  |      |j                  |      fcY d}~S # t        $ r t        dd|      w xY wd}~ww xY w)aT  
    Half extended Euclidean algorithm of ``f`` and ``g``.

    Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``.

    Examples
    ========

    >>> from sympy import half_gcdex
    >>> from sympy.abc import x

    >>> half_gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4)
    (3/5 - x/5, x + 1)

    r  rO  Nr  r  rX  )rl   rI  r/  r<   r(   r.  r  r   rn   r=   r  rO  rZ   )r\   r]   rV   r{   r   r   r|   r|  rP   r  r  r  r  s                ra   r  r    s   " $ 12
:-q!fDtDtDA <<<)DAq99yy{AIIK''!t  :)#))4A	:$$Q*DAq ??1%vq'999 # 	:#L!S99	::s5   B 	D
C<&C";!C<D"C99C<<Dc                 L   t        j                  |ddg       	 t        | |fg|i |\  \  }}}|j                  ||j                        \  }}}|j                  s/|j                         |j                         |j                         fS |||fS # t        $ r}t	        |j
                        \  }\  }	}
	 |j                  |	|
      \  }}}|j                  |      |j                  |      |j                  |      fcY d}~S # t        $ r t        dd|      w xY wd}~ww xY w)aZ  
    Extended Euclidean algorithm of ``f`` and ``g``.

    Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``.

    Examples
    ========

    >>> from sympy import gcdex
    >>> from sympy.abc import x

    >>> gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4)
    (3/5 - x/5, x**2/5 - 6*x/5 + 2, x + 1)

    r  rO  Nr  r  rX  )rl   rI  r/  r<   r(   r.  r  r   rn   r=   r  rO  rZ   )r\   r]   rV   r{   r   r   r|   r|  rP   r  r  r  r  r  s                 ra   r  r  )  s   " $ 12
N-q!fDtDtDA ggachhg'GAq!99yy{AIIK44!Qw  N)#))4A	Nll1a(GAq! ??1%vq'96??1;MMM # 	5#GQ44	5Ns5   B 	D#D7D1D>D#DDD#c                    t        j                  |ddg       	 t        | |fg|i |\  \  }}}|j                  ||j                        }|j                  s|j                         S |S # t        $ ra}t	        |j
                        \  }\  }	}
	 |j                  |j                  |	|
            cY d}~S # t        $ r t        dd|      w xY wd}~ww xY w)a/  
    Invert ``f`` modulo ``g`` when possible.

    Examples
    ========

    >>> from sympy import invert, S, mod_inverse
    >>> from sympy.abc import x

    >>> invert(x**2 - 1, 2*x - 1)
    -4/3

    >>> invert(x**2 - 1, x - 1)
    Traceback (most recent call last):
    ...
    NotInvertible: zero divisor

    For more efficient inversion of Rationals,
    use the :obj:`sympy.core.intfunc.mod_inverse` function:

    >>> mod_inverse(3, 5)
    2
    >>> (S(2)/5).invert(S(7)/3)
    5/2

    See Also
    ========
    sympy.core.intfunc.mod_inverse

    r  rO  Nr  r  rX  )rl   rI  r/  r<   r(   r.  r   r  rn   r=   r  rO  rZ   )r\   r]   rV   r{   r   r   r|   r|  rP   r  r  r  s               ra   r  r  P  s    @ $ 126-q!fDtDtDA 	
"A99yy{  6)#))4A	6??6==A#677" 	6#Ha55	66s/   A, ,	C5C B71C7CCCc                     t        j                  |dg       	 t        | |fg|i |\  \  }}}|j                  |      }|j                  s|D 	cg c]  }	|	j                          c}	S |S # t        $ r}t	        dd|      d}~ww xY wc c}	w )z
    Compute subresultant PRS of ``f`` and ``g``.

    Examples
    ========

    >>> from sympy import subresultants
    >>> from sympy.abc import x

    >>> subresultants(x**2 + 1, x**2 - 1)
    [x**2 + 1, x**2 - 1, -2]

    rO  r  r  N)rl   rI  r/  r<   r=   r  rO  rZ   )
r\   r]   rV   r{   r   r   r|   r|  r_   ru  s
             ra   r  r    s     $	*9-q!fDtDtDA __QF99%+,		,,  9C889 -s   A- B-	B6BBFr  c                   t        j                  |dg       	 t        | |fg|i |\  \  }}}|r|j                  ||      \  }	}
n|j                  |      }	|j                  s@|r.|	j                         
D cg c]  }|j                          c}fS |	j                         S |r|	
fS |	S # t        $ r}t	        dd|      d}~ww xY wc c}w )z
    Compute resultant of ``f`` and ``g``.

    Examples
    ========

    >>> from sympy import resultant
    >>> from sympy.abc import x

    >>> resultant(x**2 + 1, x**2 - 1)
    4

    rO  r  r  Nr  )rl   rI  r/  r<   r=   r  rO  rZ   )r\   r]   r  rV   r{   r   r   r|   r|  r_   r  ru  s               ra   r  r    s     $	*5-q!fDtDtDA KKjK9	Q99>>#1%=aaiik%===~~19  5Q445 &>s   B. ;C.	C	7CC	c                     t        j                  |dg       	 t        | g|i |\  }}|j                         }|j                  s|j                         S |S # t        $ r}t	        dd|      d}~ww xY w)z
    Compute discriminant of ``f``.

    Examples
    ========

    >>> from sympy import discriminant
    >>> from sympy.abc import x

    >>> discriminant(x**2 + 2*x + 3)
    -8

    rO  r  r   N)rl   rI  r'  r<   r=   r  rO  rZ   r\   rV   r{   r   r|   r|  r_   s          ra   r  r    s{     $	*81D1D13 ^^F99~~  83778   A 	A4"A//A4c                 2   t        j                  |dg       	 t        | |fg|i |\  \  }}}|j                  |      \  }}}|j                  s/|j                         |j                         |j                         fS |||fS # t        $ r}t	        |j
                        \  }\  }	}
	 |j                  |	|
      \  }}}|j                  |      |j                  |      |j                  |      fcY d}~S # t        $ r t        dd|      w xY wd}~ww xY w)a  
    Compute GCD and cofactors of ``f`` and ``g``.

    Returns polynomials ``(h, cff, cfg)`` such that ``h = gcd(f, g)``, and
    ``cff = quo(f, h)`` and ``cfg = quo(g, h)`` are, so called, cofactors
    of ``f`` and ``g``.

    Examples
    ========

    >>> from sympy import cofactors
    >>> from sympy.abc import x

    >>> cofactors(x**2 - 1, x**2 - 3*x + 2)
    (x - 1, x + 1, x - 2)

    rO  Nr  r  )rl   rI  r/  r<   r(   r.  r  r   rn   r=   rO  rZ   )r\   r]   rV   r{   r   r   r|   r|  rP   r  r  r  r  r  s                 ra   r  r    s   & $	*
R-q!fDtDtDA ++a.KAsC99yy{CKKM3;;=88#s{  R)#))4A	R **1a0KAsC ??1%vs';V__S=QQQ # 	9#KC88	9Rs5   B 	DD*C7 1D1D7DDDc                 0   t        |       } fd} ||       }||S t        j                  dg       	 t        | gi \  }}t	        |       dkD  rt        d | D              rn| d   }| dd D cg c]  }||z  j                          }	}t        d |	D              r4d}
|	D ]  }t        |
|j                         d         }
! t        ||
z        S |s)|j                  st        j                  S t!        d|
      S |d   |dd }}|D ]!  }|j#                  |      }|j$                  s! n |j                  s|j'                         S |S c c}w # t        $ r6} ||j                        }||cY d}~S t        d	t	        |       |      d}~ww xY w)z
    Compute GCD of a list of polynomials.

    Examples
    ========

    >>> from sympy import gcd_list
    >>> from sympy.abc import x

    >>> gcd_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2])
    x - 1

    c                     sqsot        |       \  }}|s|j                  S |j                  rG|d   |dd  }}|D ]'  }|j                  ||      }|j	                  |      s' n |j                  |      S y Nr   r   )r(   r   rO  r  r  r   seqrP   numbersr_   numberr{   rV   s        ra   try_non_polynomial_gcdz(gcd_list.<locals>.try_non_polynomial_gcd  s    D.s3OFG{{"$$")!*gabk% F#ZZ7F}}V,	 v..rd   NrO  r   c              3   P   K   | ]  }|j                   xr |j                     y wr   is_algebraicis_irrational.0r  s     ra   	<genexpr>zgcd_list.<locals>.<genexpr>=  $     V3 0 0 FS5F5F FV   $&r  c              3   4   K   | ]  }|j                     y wr   is_rationalrt  frcs     ra   ru  zgcd_list.<locals>.<genexpr>@       2s3??2   r   gcd_listr   )r"   rl   rI  r/  r   r  ratsimpr  as_numer_denomrc  r<   r.  r=   rO  r   rB  rT   r  r  rZ   )rk  rV   r{   rn  r_   rO  r|   r  r  lstlcr|  r|  rD  s    ``           ra   r  r    s    #,C& $C(F$	*?,S@4@4@
s s8a<CVRUVVBA14Sb;#QsUOO%;C;2c22 :CR!3!3!5a!89B: 1R4y  yy66Ms##!HeABiEF D!==	 99~~C <  ?'		2M#JC#>>?s6   >E 6EAE E 	FF4F:FFc                    t        | d      r||f|z   }t        | g|i |S |t        d      t        j                  |dg       	 t        | |fg|i |\  \  }}}t        t        | |f      \  }}|j                  rb|j                  rV|j                  rJ|j                  r>||z  j                         }	|	j                  rt        ||	j                         d   z        S |j%                  |      }|j*                  s|j-                         S |S # t        $ ra}
t        |
j                         \  }\  }}	 |j#                  |j%                  ||            cY d}
~
S # t&        $ r t)        dd|
      w xY wd}
~
ww xY w)z
    Compute GCD of ``f`` and ``g``.

    Examples
    ========

    >>> from sympy import gcd
    >>> from sympy.abc import x

    >>> gcd(x**2 - 1, x**2 - 3*x + 2)
    x - 1

    __iter__Nz2gcd() takes 2 arguments or a sequence of argumentsrO  r   r  r  )r  r  r  rl   rI  r/  r   r"   rq  rr  r  rz  rc  r  r<   r(   r.  r   r  rn   r=   rO  rZ   r\   r]   rV   r{   r   r   r|   r  r  r|  r|  rP   r_   s                ra   r  r  c  sj    q*=4$;D)D)D))	
LMM$	*3-q!fDtDtDA 7QF#1>>aoo!..Q__Q3--/C1S//1!4455 UU1XF99~~  3)#))4A	3??6::a#344" 	3#E1c22	33s1   	BD 	E<E77 EE<E44E77E<c                    t        |       } dt        t           ffd} ||       }||S t        j                  dg       	 t        | gi \  }}t        |       dkD  rwt        d | D              re| d   }| dd D cg c]  }||z  j                          }	}t        d |	D              r+d}
|	D ]  }t        |
|j                         d         }
! ||
z  S |s)|j                  st        j                   S t#        d|
      S |d   |dd }}|D ]  }|j                  |      } |j                  s|j%                         S |S c c}w # t        $ r6} ||j                        }||cY d}~S t        d	t        |       |      d}~ww xY w)z
    Compute LCM of a list of polynomials.

    Examples
    ========

    >>> from sympy import lcm_list
    >>> from sympy.abc import x

    >>> lcm_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2])
    x**5 - x**4 - 2*x**3 - x**2 + x + 2

    returnc                     smskt        |       \  }}|s|j                  |j                        S |j                  r4|d   |dd  }}|D ]  }|j	                  ||      } |j                  |      S y ri  )r(   r   r   rO  r  rj  s        ra   try_non_polynomial_lcmz(lcm_list.<locals>.try_non_polynomial_lcm  s{    D.s3OFGvzz22$$")!*gabk% 8F#ZZ7F8 v..rd   NrO  r   c              3   P   K   | ]  }|j                   xr |j                     y wr   rp  rs  s     ra   ru  zlcm_list.<locals>.<genexpr>  rv  rw  r  c              3   4   K   | ]  }|j                     y wr   ry  r{  s     ra   ru  zlcm_list.<locals>.<genexpr>  r}  r~  lcm_listr   r   )r"   r   r	   rl   rI  r/  r   r  r  r  r  r<   r.  r=   rO  r   r  rT   rZ   )rk  rV   r{   r  r_   rO  r|   r  r  r  r  r|  r|  rD  s    ``           ra   r  r    s    #,Cx~   $C(F$	*?,S@4@4@
s s8a<CVRUVVBA14Sb;#QsUOO%;C;2c22 :CR!3!3!5a!89B:t yy55Ls##!HeABiEF "D!" 99~~; <  ?'		2M#JC#>>?s6   >E E>E E 	FF+F1FFc                    t        | d      r||f|z   }t        | g|i |S |t        d      t        j                  |dg       	 t        | |fg|i |\  \  }}}t        t        | |f      \  }}|j                  rY|j                  rM|j                  rA|j                  r5||z  j                         }	|	j                  r||	j                         d   z  S |j#                  |      }|j(                  s|j+                         S |S # t        $ ra}
t        |
j                        \  }\  }}	 |j!                  |j#                  ||            cY d}
~
S # t$        $ r t'        dd|
      w xY wd}
~
ww xY w)z
    Compute LCM of ``f`` and ``g``.

    Examples
    ========

    >>> from sympy import lcm
    >>> from sympy.abc import x

    >>> lcm(x**2 - 1, x**2 - 3*x + 2)
    x**3 - 2*x**2 - x + 2

    r  Nz2lcm() takes 2 arguments or a sequence of argumentsrO  r   r  r  )r  r  r  rl   rI  r/  r   r"   rq  rr  r  rz  r  r<   r(   r.  r   r  rn   r=   rO  rZ   r  s                ra   r  r    se    q*=4$;D)D)D))	
LMM$	*3-q!fDtDtDA 7QF#1>>aoo!..Q__Q3--/C++-a000 UU1XF99~~  3)#))4A	3??6::a#344" 	3#E1c22	33s1   	BD	 		E3E.. EE3E++E..E3c           
      6   t        |       }t        | t              r(t        fd| j                  | j                  fD         S t        | t
              rt        d|       t        | t              r| j                  r|S j                  dd      rY | j                  | j                  D cg c]  }t        |gi  c} }j                  d       dd<   t        |gi S j                  dd      }t        j                  dg       	 t!        | gi \  }}|j                         \  }
} |j&                  j(                  rZ|j&                  j*                  r| j-                  d
      \  }} | j/                         \  }} |j&                  j*                  r|z  }nt0        j2                  }t5        t7        | j8                  |
      D cg c]
  \  }}||z   c}} }t;        |d      rt0        j2                  }|dk(  r|S |rt=        ||| j?                         z        S t=        || j?                         d      jA                         \  }} t=        ||| z  d      S c c}w # t"        $ r}	|	j$                  cY d	}	~	S d	}	~	ww xY wc c}}w )az  
    Remove GCD of terms from ``f``.

    If the ``deep`` flag is True, then the arguments of ``f`` will have
    terms_gcd applied to them.

    If a fraction is factored out of ``f`` and ``f`` is an Add, then
    an unevaluated Mul will be returned so that automatic simplification
    does not redistribute it. The hint ``clear``, when set to False, can be
    used to prevent such factoring when all coefficients are not fractions.

    Examples
    ========

    >>> from sympy import terms_gcd, cos
    >>> from sympy.abc import x, y
    >>> terms_gcd(x**6*y**2 + x**3*y, x, y)
    x**3*y*(x**3*y + 1)

    The default action of polys routines is to expand the expression
    given to them. terms_gcd follows this behavior:

    >>> terms_gcd((3+3*x)*(x+x*y))
    3*x*(x*y + x + y + 1)

    If this is not desired then the hint ``expand`` can be set to False.
    In this case the expression will be treated as though it were comprised
    of one or more terms:

    >>> terms_gcd((3+3*x)*(x+x*y), expand=False)
    (3*x + 3)*(x*y + x)

    In order to traverse factors of a Mul or the arguments of other
    functions, the ``deep`` hint can be used:

    >>> terms_gcd((3 + 3*x)*(x + x*y), expand=False, deep=True)
    3*x*(x + 1)*(y + 1)
    >>> terms_gcd(cos(x + x*y), deep=True)
    cos(x*(y + 1))

    Rationals are factored out by default:

    >>> terms_gcd(x + y/2)
    (2*x + y)/2

    Only the y-term had a coefficient that was a fraction; if one
    does not want to factor out the 1/2 in cases like this, the
    flag ``clear`` can be set to False:

    >>> terms_gcd(x + y/2, clear=False)
    x + y/2
    >>> terms_gcd(x*y/2 + y**2, clear=False)
    y*(x/2 + y)

    The ``clear`` flag is ignored if all coefficients are fractions:

    >>> terms_gcd(x/3 + y/2, clear=False)
    (2*x + 3*y)/6

    See Also
    ========
    sympy.core.exprtools.gcd_terms, sympy.core.exprtools.factor_terms

    c              3   <   K   | ]  }t        |gi   y wr   )rU  )rt  r  r{   rV   s     ra   ru  zterms_gcd.<locals>.<genexpr>^  s      N!)A555Ns   z3Inequalities cannot be used with terms_gcd. Found: deepFr)  clearTrO  Nr  r   )r  )!r"   rS   r   lhsrhsr   r  r	   is_Atomr  r`   r{   rU  poprl   rI  r'  r<   r   rP   r  r  r  r  r   r  r   r   rV   r   r   rZ   as_coeff_Mul)r\   rV   r{   r*  r  r   r  r   r|   r|  r   denomr   r  r   terms    ``             ra   rU  rU    s3   F 1:D!XNquu~NOO	Az	"RSUVVa!))xxaffAFFCqy2T2T2CDX,t,t,,HHWd#E$	*1D1D13 ;;=DAq
zz::~~d~3HE1;;=q::UNE#affa.1$!QA12DE119K5$qyy{"233 5!))+U;HHJHE1ud1fE22K D  xx  2s*   .I.I3 J
3	J<JJJc                    t        j                  |ddg       	 t        | g|i |\  }}|j                  t        |            }|j                  s|j                         S |S # t        $ r}t	        dd|      d}~ww xY w)z
    Reduce ``f`` modulo a constant ``p``.

    Examples
    ========

    >>> from sympy import trunc
    >>> from sympy.abc import x

    >>> trunc(2*x**3 + 3*x**2 + 5*x + 7, 3)
    -x**3 - x + 1

    r  rO  r  r   N)	rl   rI  r'  r<   r=   r  r"   rO  rZ   )r\   r  rV   r{   r   r|   r|  r_   s           ra   r  r    s     $ 1211D1D13 WWWQZ F99~~  1C001s   A$ $	A?-A::A?c                    t        j                  |ddg       	 t        | g|i |\  }}|j                  |j                        }|j                  s|j                         S |S # t        $ r}t	        dd|      d}~ww xY w)z
    Divide all coefficients of ``f`` by ``LC(f)``.

    Examples
    ========

    >>> from sympy import monic
    >>> from sympy.abc import x

    >>> monic(3*x**2 + 4*x + 2)
    x**2 + 4*x/3 + 2/3

    r  rO  r  r   NrX  )	rl   rI  r'  r<   r=   r  r  rO  rZ   rd  s          ra   r  r    s     $ 1211D1D13 WW#((W#F99~~  1C001s   A& &	B/A<<Bc                     t        j                  |dg       	 t        | g|i |\  }}|j                         S # t        $ r}t	        dd|      d}~ww xY w)z
    Compute GCD of coefficients of ``f``.

    Examples
    ========

    >>> from sympy import content
    >>> from sympy.abc import x

    >>> content(6*x**2 + 8*x + 12)
    2

    rO  r  r   N)rl   rI  r'  r<   r=   r  rL  s         ra   r  r    sb     $	*31D1D13 99;  3	1c223s   ; 	AAAc                     t        j                  |dg       	 t        | g|i |\  }}|j                         \  }}|j                  s||j                         fS ||fS # t        $ r}t	        dd|      d}~ww xY w)a  
    Compute content and the primitive form of ``f``.

    Examples
    ========

    >>> from sympy.polys.polytools import primitive
    >>> from sympy.abc import x

    >>> primitive(6*x**2 + 8*x + 12)
    (2, 3*x**2 + 4*x + 6)

    >>> eq = (2 + 2*x)*x + 2

    Expansion is performed by default:

    >>> primitive(eq)
    (2, x**2 + x + 1)

    Set ``expand`` to False to shut this off. Note that the
    extraction will not be recursive; use the as_content_primitive method
    for recursive, non-destructive Rational extraction.

    >>> primitive(eq, expand=False)
    (1, x*(2*x + 2) + 2)

    >>> eq.as_content_primitive()
    (2, x*(x + 1) + 1)

    rO  r  r   N)rl   rI  r'  r<   r=   r  rO  rZ   )r\   rV   r{   r   r|   r|  r   r_   s           ra   r  r    s    @ $	*51D1D13 ;;=LD&99V^^%%%V|  5Q445s   A   	A;)A66A;c                     t        j                  |dg       	 t        | |fg|i |\  \  }}}|j                  |      }|j                  s|j                         S |S # t        $ r}t	        dd|      d}~ww xY w)z
    Compute functional composition ``f(g)``.

    Examples
    ========

    >>> from sympy import compose
    >>> from sympy.abc import x

    >>> compose(x**2 + x, x - 1)
    x**2 - x

    rO  r  r  N)rl   rI  r/  r<   r=   r  rO  rZ   )	r\   r]   rV   r{   r   r   r|   r|  r_   s	            ra   r  r    s     $	*3-q!fDtDtDA YYq\F99~~  3	1c223rS  c                    t        j                  |dg       	 t        | g|i |\  }}|j                         }|j                  s|D cg c]  }|j                          c}S |S # t        $ r}t	        dd|      d}~ww xY wc c}w )z
    Compute functional decomposition of ``f``.

    Examples
    ========

    >>> from sympy import decompose
    >>> from sympy.abc import x

    >>> decompose(x**4 + 2*x**3 - x - 1)
    [x**2 - x - 1, x**2 + x]

    rO  r  r   N)rl   rI  r'  r<   r=   r  rO  rZ   r\   rV   r{   r   r|   r|  r_   ru  s           ra   r  r  /  s     $	*51D1D13 [[]F99%+,		,,  5Q445 -s   A' B'	B0A==Bc                 .   t        j                  |ddg       	 t        | g|i |\  }}|j                  |j                        }|j                  s|D cg c]  }|j                          c}S |S # t        $ r}t	        dd|      d}~ww xY wc c}w )z
    Compute Sturm sequence of ``f``.

    Examples
    ========

    >>> from sympy import sturm
    >>> from sympy.abc import x

    >>> sturm(x**3 - 2*x**2 + x - 3)
    [x**3 - 2*x**2 + x - 3, 3*x**2 - 4*x + 1, 2*x/9 + 25/9, -2079/4]

    r  rO  r  r   NrX  )	rl   rI  r'  r<   r=   r  r  rO  rZ   r  s           ra   r  r  M  s     $ 1211D1D13 WW#((W#F99%+,		,,  1C001 -s   A4 B4	B=B

Bc                 $   t        j                  |dg       	 t        | g|i |\  }}|j                         }|j                  s%|D cg c]  \  }}|j                         |f c}}S |S # t        $ r}t	        dd|      d}~ww xY wc c}}w )a&  
    Compute a list of greatest factorial factors of ``f``.

    Note that the input to ff() and rf() should be Poly instances to use the
    definitions here.

    Examples
    ========

    >>> from sympy import gff_list, ff, Poly
    >>> from sympy.abc import x

    >>> f = Poly(x**5 + 2*x**4 - x**3 - 2*x**2, x)

    >>> gff_list(f)
    [(Poly(x, x, domain='ZZ'), 1), (Poly(x + 2, x, domain='ZZ'), 4)]

    >>> (ff(Poly(x), 1)*ff(Poly(x + 2), 4)) == f
    True

    >>> f = Poly(x**12 + 6*x**11 - 11*x**10 - 56*x**9 + 220*x**8 + 208*x**7 -         1401*x**6 + 1090*x**5 + 2715*x**4 - 6720*x**3 - 1092*x**2 + 5040*x, x)

    >>> gff_list(f)
    [(Poly(x**3 + 7, x, domain='ZZ'), 2), (Poly(x**2 + 5*x, x, domain='ZZ'), 3)]

    >>> ff(Poly(x**3 + 7, x), 2)*ff(Poly(x**2 + 5*x, x), 3) == f
    True

    rO  r  r   N)rl   rI  r'  r<   r=   r  rO  rZ   )	r\   rV   r{   r   r|   r|  r  r]   rR  s	            ra   r  r  k  s    @ $	*41D1D13 jjlG99-45TQa 55  4
As334 6s   A. B.	B	7BB	c                     t        d      )z3Compute greatest factorial factorization of ``f``. zsymbolic falling factorialr  r\   rV   r{   s      ra   gffr    s     :
;;rd   c                 X   t        j                  |dg       	 t        | g|i |\  }}|j                         \  }}}|D 	cg c]  }	t        |	       }
}	|j                  s!|
|j                         |j                         fS |
||fS # t        $ r}t	        dd|      d}~ww xY wc c}	w )a  
    Compute square-free norm of ``f``.

    Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and
    ``r(x) = Norm(g(x))`` is a square-free polynomial over ``K``,
    where ``a`` is the algebraic extension of the ground domain.

    Examples
    ========

    >>> from sympy import sqf_norm, sqrt
    >>> from sympy.abc import x

    >>> sqf_norm(x**2 + 1, extension=[sqrt(3)])
    ([1], x**2 - 2*sqrt(3)*x + 4, x**4 - 4*x**2 + 16)

    rO  r  r   N)	rl   rI  r'  r<   r=   r  r   rO  rZ   )r\   rV   r{   r   r|   r|  r  r]   ru  sis_exprs              ra   r  r    s    & $	*41D1D13 jjlGAq!$%&bgbk&F&99qyy{AIIK//q!|  4
As334
 's   B	 B'		B$BB$c                     t        j                  |dg       	 t        | g|i |\  }}|j                         }|j                  s|j                         S |S # t        $ r}t	        dd|      d}~ww xY w)z
    Compute square-free part of ``f``.

    Examples
    ========

    >>> from sympy import sqf_part
    >>> from sympy.abc import x

    >>> sqf_part(x**3 - 3*x - 2)
    x**2 - x - 2

    rO  r  r   N)rl   rI  r'  r<   r=   r  rO  rZ   rd  s          ra   r  r    sz     $	*41D1D13 ZZ\F99~~  4
As334re  c                 4    |dk(  rd }nd }t        | |      S )z&Sort a list of ``(expr, exp)`` pairs. r)  c                     | \  }}|j                   j                         }|t        |      t        |j                        t	        |j
                        |fS r   rg   r=  r   rV   rp   rP   r   rD  exprg   s       ra   rk  z_sorted_factors.<locals>.key  sC    ID#((""$CS3tyy>3t{{3CSIIrd   c                     | \  }}|j                   j                         }t        |      t        |j                        |t	        |j
                        |fS r   r  r  s       ra   rk  z_sorted_factors.<locals>.key  sC    ID#((""$CHc$))nc3t{{3CSIIrd   rj  )ru  )r  methodrk  s      ra   _sorted_factorsr    s$    	J
	J
 's##rd   c                 f    t        | D cg c]  \  }}|j                         |z   c}} S c c}}w )z*Multiply a list of ``(expr, exp)`` pairs. )r   rZ   )r  r\   rR  s      ra   _factors_productr    s)    G4DAqa4554s   -
c           
         t         j                  g }}t        j                  |       D cg c]   }t	        |d      r|j                         n|" }}|D ]  }|j                  st        |t              rt        |      r||z  }1|j                  rj|j                  t         j                  k7  rM|j                  \  }}	|j                  r|	j                  r||z  }|j                  r&|j                  ||	f       |t         j                  }	}	 t        ||      \  }
}t!        |
|dz         } |       \  }}|t         j                  urV|	j"                  r	|||	z  z  }nA|j$                  r|j                  ||	f       n!|j                  |t         j                  f       |	t         j                  u r|j'                  |       o|	j(                  r+|j'                  |D cg c]  \  }}|||	z  f c}}       g }|D ]I  \  }|j+                         j$                  r|j                  ||	z  f       7|j                  |f       K |j                  t-        |      |	f        |dk(  r<|D ch c]  \  }}|	 c}}D cg c]  t3        t4        fd|D              f }}||fS c c}w c c}}w # t.        $ r(}|j                  |j0                  |	f       Y d}~d}~ww xY wc c}}w c c}w )z.Helper function for :func:`_symbolic_factor`. _eval_factor_listNr)  c              3   4   K   | ]  \  }}|k(  s|  y wr   r  )rt  r\   r   rR  s      ra   ru  z(_symbolic_factor_list.<locals>.<genexpr>+  s      Atq!!q& As   )r   r  r   	make_argsr  r  rA  rS   r	   r   is_PowbaseExp1r{   r3  r&  rY   r~  is_positiver5  
is_integerrZ   r  r<   r   r   r   )r   r|   r  r   r  r   r{   argr  r  rD  r   r`   _coeff_factorsr\   rR  r  r|  s                   `  ra   _symbolic_factor_listr    s   UUB7E t$& !(> :ANNA &D & ,?==ZT2|C7HSLEZZCHH.ID#~~#--~~c{+QUU#D	?%dC0GD! 4'!12D#vFHQUU">>VS[(E''NNFC=1OOVQUUO4aee|x(x@tq!AcE
@A$ -DAqyy{..1S5z2aV,	-  0 7=>Y,?Z +2341aQ35 3 Aw ABAF 5 5 '>g&H  A# " 	,NNCHHc?++	,< 45s/   %J.J9J33K-"K39	K*K%%K*c           
         t        | t              rOt        | d      r| j                         S t	        t        | |d         ||      \  }}t        |t        |            S t        | d      r2 | j                  | j                  D cg c]  }t        |||       c} S t        | d      r*| j                  | D cg c]  }t        |||       c}      S | S c c}w c c}w )z%Helper function for :func:`_factor`. r  fraction)r  r{   r  )rS   r	   r  r  r  rE   r   r  r`   r{   _symbolic_factorr   )r   r|   r  r   r  r  s         ra   r  r  1  s    $4'$$&&.xs:/WY\^dew5"27";<<	v	tyyS#+Cf=STT	z	"~~TRc/S&ARSS	 TRs   C9Cc                 f   t        j                  |ddg       t        j                  ||      }t        |       } t	        | t
        t        f      rHt	        | t              r| d}}nt        |       j                         \  }}t        |||      \  }}t        |||      \  }	}
|
r|j                  st        d| z        |j                  ddi      }||
fD ];  }t        |      D ]+  \  }\  }}|j                  rt        ||      \  }}||f||<   - = t!        ||      }t!        |
|      }
|j"                  sH|D cg c]  \  }}|j%                         |f }}}|
D cg c]  \  }}|j%                         |f }
}}||	z  }|j                  s||fS |||
fS t        d| z        c c}}w c c}}w )z>Helper function for :func:`sqf_list` and :func:`factor_list`. fracrO  r   za polynomial expected, got %sr)  T)rl   rI  rm   r"   rS   r	   rT   rE   r  r  r  r9   cloner   rv   r&  r  rO  rZ   )r   rV   r{   r  r|   numerr  r  fpr  fq_optr  r   r\   rR  r   r   s                     ra   _generic_factor_listr  @  s   $ 12


d
+C4=D$t%dD!5E#D>88:LE5&uc6:B&uc6:Bchh!"AD"HIIyy(D)*Bx 	(G&w/ (	6Aqyy*1d3DAq"#QGAJ(	( R(R(yy/12tq!199;"2B2/12tq!199;"2B22xx"9"b= =DEE 32s   <F' F-c                     |j                  dd      }t        j                  |g        t        j                  ||      }||d<   t	        t        |       ||      S )z4Helper function for :func:`sqf` and :func:`factor`. r  T)r  rl   rI  rm   r  r"   )r   rV   r{   r  r  r|   s         ra   _generic_factorr  l  sP    xx
D)H$#


d
+CC
OGDM377rd   c                     ddl m d	fd	}d	fd	}d }| j                         j                  rI ||       rA| j	                         } || |      }|r|d   |d   d|d   fS  || |      }|rdd|d   |d   fS y)
a!  
    try to transform a polynomial to have rational coefficients

    try to find a transformation ``x = alpha*y``

    ``f(x) = lc*alpha**n * g(y)`` where ``g`` is a polynomial with
    rational coefficients, ``lc`` the leading coefficient.

    If this fails, try ``x = y + beta``
    ``f(x) = g(y)``

    Returns ``None`` if ``g`` not found;
    ``(lc, alpha, None, g)`` in case of rescaling
    ``(None, None, beta, g)`` in case of translation

    Notes
    =====

    Currently it transforms only polynomials without roots larger than 2.

    Examples
    ========

    >>> from sympy import sqrt, Poly, simplify
    >>> from sympy.polys.polytools import to_rational_coeffs
    >>> from sympy.abc import x
    >>> p = Poly(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))}), x, domain='EX')
    >>> lc, r, _, g = to_rational_coeffs(p)
    >>> lc, r
    (7 + 5*sqrt(2), 2 - 2*sqrt(2))
    >>> g
    Poly(x**3 + x**2 - 1/4*x - 1/4, x, domain='QQ')
    >>> r1 = simplify(1/r)
    >>> Poly(lc*r**3*(g.as_expr()).subs({x:x*r1}), x, domain='EX') == p
    True

    r   simplifyNc                    t        | j                        dk(  r| j                  d   j                  sd| fS | j                         }| j	                         }|xs |j                         }|j                         dd }|D cg c]
  } |       }}t        |      dkD  r|d   r |d   |d   z        }g }t        t        |            D ]5  } ||   ||dz   z  z        }|j                  s y|j                  |       7  d|z        }	| j                  d   }
|
|z  g}t        d|dz         D ]"  }|j                  ||dz
     |
||z
  z  z         $ t        | } t        |       } ||	| fS yc c}w )a$  
        try rescaling ``x -> alpha*x`` to convert f to a polynomial
        with rational coefficients.
        Returns ``alpha, f``; if the rescaling is successful,
        ``alpha`` is the rescaling factor, and ``f`` is the rescaled
        polynomial; else ``alpha`` is ``None``.
        r   r   Nr  )r   rV   r  r  r  r  r1  r   rz  r3  r
   rT   )r\   f1r*  r  r   coeffx
rescale1_xcoeffs1r   	rescale_xr  r2  r  s               ra   _try_rescalez(to_rational_coeffs.<locals>._try_rescale  s    166{aq	':':7NHHJTTV288:$178v(6"88v;?vbz!&*VBZ"78JG3v;' (!&)JQ,?"?@))  v&	( %Qz\2	FF1ITFq!a% 8AHHWQU^AAJ678GG9a''% 9s   E2c                    t        | j                        dk(  r| j                  d   j                  sd| fS | j                         }|xs |j	                         }|j                         dd } 	|d         }|j                  rP|j                  sDt        |j                  d d      \  }} |j                  |  |z  }|j                  |      }||fS y)a+  
        try translating ``x -> x + alpha`` to convert f to a polynomial
        with rational coefficients.
        Returns ``alpha, f``; if the translating is successful,
        ``alpha`` is the translating factor, and ``f`` is the shifted
        polynomial; else ``alpha`` is ``None``.
        r   r   Nc                     | j                   du S r  ry  )zs    ra   ri  z<to_rational_coeffs.<locals>._try_translate.<locals>.<lambda>  s    !--4/ rd   Tbinary)r   rV   r  r  r  r1  is_Addrz  rL   r{   r`   r  )
r\   r  r*  r   r   ratnonratalphaf2r  s
            ra   _try_translatez*to_rational_coeffs.<locals>._try_translate  s     166{aq	':':7NHHJ288:$VAY88AMMqvv/>KCQVVV_$Q&E%B"9rd   c                    | j                         }d}|D ]  }t        j                  |      D ]  }t        |      j                  }|j                         D cg c]8  \  }}|j                  r'|j                  r|j                  dk\  r|j                  : }}}|snt        |      dk(  rd}t        |      dkD  s  y  |S c c}}w )zS
        Return True if ``f`` is a sum with square roots but no other root
        Fr  T)r   r
   r  r   r  r   r   is_Rationalrt  minr  )	r  r   has_sqr  r  r\   r  wxru  s	            ra   _has_square_rootsz-to_rational_coeffs.<locals>._has_square_roots  s      
	!A]]1% 	!AJ&&'(wwy BeaKKBNNrttqy TT B Bq6Q;!Fq6A: 	!
	! Bs   =C
r   r  r   )sympy.simplify.simplifyr  r   r   r  )r\   r  r  r  r  ru  r  s         @ra   to_rational_coeffsr  u  s    L 1 D,& 	||~ 1! 4WWYBQ41tQqT))q"%AT1Q41--rd   c           
         ddl m} t        | |d      }|j                         }t	        |      }|sy|\  }}}}	t        |	j                               }
|re ||
d   |z  ||z  z        } |d|z        }g }|
dd d   D ]5  }|j                   ||d   j                  |||z  i            |d   f       7 ||fS |
d   }g }|
dd d   D ]/  }|j                  |d   j                  |||z
  i      |d   f       1 ||fS )a  
    helper function to factor polynomial using to_rational_coeffs

    Examples
    ========

    >>> from sympy.polys.polytools import _torational_factor_list
    >>> from sympy.abc import x
    >>> from sympy import sqrt, expand, Mul
    >>> p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))}))
    >>> factors = _torational_factor_list(p, x); factors
    (-2, [(-x*(1 + sqrt(2))/2 + 1, 1), (-x*(1 + sqrt(2)) - 1, 1), (-x*(1 + sqrt(2)) + 1, 1)])
    >>> expand(factors[0]*Mul(*[z[0] for z in factors[1]])) == p
    True
    >>> p = expand(((x**2-1)*(x-2)).subs({x:x + sqrt(2)}))
    >>> factors = _torational_factor_list(p, x); factors
    (1, [(x - 2 + sqrt(2), 1), (x - 1 + sqrt(2), 1), (x + 1 + sqrt(2), 1)])
    >>> expand(factors[0]*Mul(*[z[0] for z in factors[1]])) == p
    True

    r   r  EXr$  Nr   )	r  r  rT   r  r  r  rZ   r3  r   )r  r  r  p1r*  resr  ru  r  r]   r  r   r1r  r  s                  ra   _torational_factor_listr    s,   , 1	a4	 B
		A
R
 CKB1a!))+&G	WQZ]1a4'(ac]Q 	=AHHhqtyy!QrT34ad;<	= q6M	 AJQ 	4AHHadiiAE
+QqT23	4q6Mrd   c                      t        | ||d      S )z
    Compute a list of square-free factors of ``f``.

    Examples
    ========

    >>> from sympy import sqf_list
    >>> from sympy.abc import x

    >>> sqf_list(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16)
    (2, [(x + 1, 2), (x + 2, 3)])

    r)  r  r  r  s      ra   r  r     s      4e<<rd   c                      t        | ||d      S )z
    Compute square-free factorization of ``f``.

    Examples
    ========

    >>> from sympy import sqf
    >>> from sympy.abc import x

    >>> sqf(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16)
    2*(x + 1)**2*(x + 2)**3

    r)  r  )r  r  s      ra   r)  r)  2  s     1dD77rd   c                      t        | ||d      S )a  
    Compute a list of irreducible factors of ``f``.

    Examples
    ========

    >>> from sympy import factor_list
    >>> from sympy.abc import x, y

    >>> factor_list(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y)
    (2, [(x + y, 1), (x**2 + 1, 2)])

    r{  r  r  r  s      ra   r  r  D  s      4h??rd   )r  c                   t        |       } |ryfd}t        | |      } i }| j                  t        t              }|D ]5  }t        |gi }|j                  s|j                  s+||k7  s1|||<   7 | j                  |      S 	 t        | d      S # t        $ r | j                  st        |       cY S  w xY w)a  
    Compute the factorization of expression, ``f``, into irreducibles. (To
    factor an integer into primes, use ``factorint``.)

    There two modes implemented: symbolic and formal. If ``f`` is not an
    instance of :class:`Poly` and generators are not specified, then the
    former mode is used. Otherwise, the formal mode is used.

    In symbolic mode, :func:`factor` will traverse the expression tree and
    factor its components without any prior expansion, unless an instance
    of :class:`~.Add` is encountered (in this case formal factorization is
    used). This way :func:`factor` can handle large or symbolic exponents.

    By default, the factorization is computed over the rationals. To factor
    over other domain, e.g. an algebraic or finite field, use appropriate
    options: ``extension``, ``modulus`` or ``domain``.

    Examples
    ========

    >>> from sympy import factor, sqrt, exp
    >>> from sympy.abc import x, y

    >>> factor(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y)
    2*(x + y)*(x**2 + 1)**2

    >>> factor(x**2 + 1)
    x**2 + 1
    >>> factor(x**2 + 1, modulus=2)
    (x + 1)**2
    >>> factor(x**2 + 1, gaussian=True)
    (x - I)*(x + I)

    >>> factor(x**2 - 2, extension=sqrt(2))
    (x - sqrt(2))*(x + sqrt(2))

    >>> factor((x**2 - 1)/(x**2 + 4*x + 4))
    (x - 1)*(x + 1)/(x + 2)**2
    >>> factor((x**2 + 4*x + 4)**10000000*(x**2 + 1))
    (x + 2)**20000000*(x**2 + 1)

    By default, factor deals with an expression as a whole:

    >>> eq = 2**(x**2 + 2*x + 1)
    >>> factor(eq)
    2**(x**2 + 2*x + 1)

    If the ``deep`` flag is True then subexpressions will
    be factored:

    >>> factor(eq, deep=True)
    2**((x + 1)**2)

    If the ``fraction`` flag is False then rational expressions
    will not be combined. By default it is True.

    >>> factor(5*x + 3*exp(2 - 7*x), deep=True)
    (5*x*exp(7*x) + 3*exp(2))*exp(-7*x)
    >>> factor(5*x + 3*exp(2 - 7*x), deep=True, fraction=False)
    5*x + 3*exp(2)*exp(-7*x)

    See Also
    ========
    sympy.ntheory.factor_.factorint

    c                 Z    t        | gi }|j                  s|j                  r|S | S )zS
            Factor, but avoid changing the expression when unable to.
            )r{  is_Mulr  )r   rw  r{   rV   s     ra   _try_factorzfactor.<locals>._try_factor  s0     ---CzzSZZ
Krd   r{  r  )r"   r%   atomsr   r
   r{  r  r  xreplacer  r9   r  r   )	r\   r  rV   r{   r  partialsmuladdr  rw  s	     ``     ra   r{  r{  V  s    H 	
A	 a% c" 	"A*T*T*C

cjjcQh!	" zz(##q$X>> Q<	s   
B  B=;B=c           	         t        | d      s#	 t        |       } | j                  ||||||      S t	        | d      \  }}	t        |	j                        dkD  rt        t        |      D ]"  \  }
}|j                  j                         ||
<   $ |+|	j                  j                  |      }|dk  rt        d      ||	j                  j                  |      }||	j                  j                  |      }t        ||	j                  |||||      }g }|D ]S  \  \  }}}|	j                  j                  |      |	j                  j                  |      }}|j!                  ||f|f       U |S # t        $ r g cY S w xY w)	a/  
    Compute isolating intervals for roots of ``f``.

    Examples
    ========

    >>> from sympy import intervals
    >>> from sympy.abc import x

    >>> intervals(x**2 - 3)
    [((-2, -1), 1), ((1, 2), 1)]
    >>> intervals(x**2 - 3, eps=1e-2)
    [((-26/15, -19/11), 1), ((19/11, 26/15), 1)]

    r  r$  r*   r$  r   r   r"  )r%  r&  r'  r  r(  )r  rT   r8   r#  r/  r   rV   r:   r   rg   r=  rP   r   r  rF   r   r3  )r   r  r%  r&  r'  r  r(  r)  rO  r|   r   rD  r#  r_   r  r  r  s                    ra   r#  r#    s   " 1j!	QA {{s#Dc{RR,Qt<
ssxx=1-- ' 	*GAtxx'')E!H	* ?**$$S)Cax !DEE?**$$S)C?**$$S)C/szz#f4A	 ( 	-OFQG::&&q)3::+>+>q+AqAMMAq67+,	- C   	I	s   E- -E;:E;c                     	 t        |       }t        | t               s!|j                  j                  st	        d      |j                  ||||||      S # t
        $ r t	        d| z        w xY w)z
    Refine an isolating interval of a root to the given precision.

    Examples
    ========

    >>> from sympy import refine_root
    >>> from sympy.abc import x

    >>> refine_root(x**2 - 3, 1, 2, eps=1e-2)
    (19/11, 26/15)

    generator must be a Symbolz,Cannot refine a root of %s, not a polynomial)r%  r:  r(  r<  )rT   rS   r   	is_Symbolr9   r8   r9  )r\   r  r  r%  r:  r(  r<  r   s           ra   r9  r9    sz    	@G!T"155?? "">??
 ==A3e$)=TT	  @:Q>@ 	@@s   <A A-c                     	 t        | d      }t        | t               s!|j                  j                  st	        d      |j                  ||      S # t
        $ r t	        d| z        w xY w)a  
    Return the number of roots of ``f`` in ``[inf, sup]`` interval.

    If one of ``inf`` or ``sup`` is complex, it will return the number of roots
    in the complex rectangle with corners at ``inf`` and ``sup``.

    Examples
    ========

    >>> from sympy import count_roots, I
    >>> from sympy.abc import x

    >>> count_roots(x**4 - 4, -3, 3)
    2
    >>> count_roots(x**4 - 4, 0, 1 + 3*I)
    1

    Fgreedyr  z*Cannot count roots of %s, not a polynomialrA  )rT   rS   r   r  r9   r8   rJ  )r\   r&  r'  r   s       ra   rJ  rJ    so    (P5!!T"155?? "">?? ==Sc=**  PJQNOOP   >A A+Tc                     	 t        | d      }t        | t               s!|j                  j                  st	        d      |j                  ||      S # t
        $ r t	        d| z        w xY w)a,  
    Returns the real and complex roots of ``f`` with multiplicities.

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

    Finds all real and complex roots of a univariate polynomial with rational
    coefficients of any degree exactly. The roots are represented in the form
    given by :func:`~.rootof`. This is equivalent to using :func:`~.rootof` to
    find each of the indexed roots.

    Examples
    ========

    >>> from sympy import all_roots
    >>> from sympy.abc import x, y

    >>> print(all_roots(x**3 + 1))
    [-1, 1/2 - sqrt(3)*I/2, 1/2 + sqrt(3)*I/2]

    Simple radical formulae are used in some cases but the cubic and quartic
    formulae are avoided. Instead most non-rational roots will be represented
    as :class:`~.ComplexRootOf`:

    >>> print(all_roots(x**3 + x + 1))
    [CRootOf(x**3 + x + 1, 0), CRootOf(x**3 + x + 1, 1), CRootOf(x**3 + x + 1, 2)]

    All roots of any polynomial with rational coefficients of any degree can be
    represented using :py:class:`~.ComplexRootOf`. The use of
    :py:class:`~.ComplexRootOf` bypasses limitations on the availability of
    radical formulae for quintic and higher degree polynomials _[1]:

    >>> p = x**5 - x - 1
    >>> for r in all_roots(p): print(r)
    CRootOf(x**5 - x - 1, 0)
    CRootOf(x**5 - x - 1, 1)
    CRootOf(x**5 - x - 1, 2)
    CRootOf(x**5 - x - 1, 3)
    CRootOf(x**5 - x - 1, 4)
    >>> [r.evalf(3) for r in all_roots(p)]
    [1.17, -0.765 - 0.352*I, -0.765 + 0.352*I, 0.181 - 1.08*I, 0.181 + 1.08*I]

    Irrational algebraic or transcendental coefficients cannot currently be
    handled by :func:`all_roots` (or :func:`~.rootof` more generally):

    >>> from sympy import sqrt, expand
    >>> p = expand((x - sqrt(2))*(x - sqrt(3)))
    >>> print(p)
    x**2 - sqrt(3)*x - sqrt(2)*x + sqrt(6)
    >>> all_roots(p)
    Traceback (most recent call last):
    ...
    NotImplementedError: sorted roots not supported over EX

    In the case of algebraic or transcendental coefficients
    :func:`~.ground_roots` might be able to find some roots by factorisation:

    >>> from sympy import ground_roots
    >>> ground_roots(p, x, extension=True)
    {sqrt(2): 1, sqrt(3): 1}

    If the coefficients are numeric then :func:`~.nroots` can be used to find
    all roots approximately:

    >>> from sympy import nroots
    >>> nroots(p, 5)
    [1.4142, 1.732]

    If the coefficients are symbolic then :func:`sympy.polys.polyroots.roots`
    or :func:`~.ground_roots` should be used instead:

    >>> from sympy import roots, ground_roots
    >>> p = x**2 - 3*x*y + 2*y**2
    >>> roots(p, x)
    {y: 1, 2*y: 1}
    >>> ground_roots(p, x)
    {y: 1, 2*y: 1}

    Parameters
    ==========

    f : :class:`~.Expr` or :class:`~.Poly`
        A univariate polynomial with rational (or ``Float``) coefficients.
    multiple : ``bool`` (default ``True``).
        Whether to return a ``list`` of roots or a list of root/multiplicity
        pairs.
    radicals : ``bool`` (default ``True``)
        Use simple radical formulae rather than :py:class:`~.ComplexRootOf` for
        some irrational roots.

    Returns
    =======

    A list of :class:`~.Expr` (usually :class:`~.ComplexRootOf`) representing
    the roots is returned with each root repeated according to its multiplicity
    as a root of ``f``. The roots are always uniquely ordered with real roots
    coming before complex roots. The real roots are in increasing order.
    Complex roots are ordered by increasing real part and then increasing
    imaginary part.

    If ``multiple=False`` is passed then a list of root/multiplicity pairs is
    returned instead.

    If ``radicals=False`` is passed then all roots will be represented as
    either rational numbers or :class:`~.ComplexRootOf`.

    See also
    ========

    Poly.all_roots:
        The underlying :class:`Poly` method used by :func:`~.all_roots`.
    rootof:
        Compute a single numbered root of a univariate polynomial.
    real_roots:
        Compute all the real roots using :func:`~.rootof`.
    ground_roots:
        Compute some roots in the ground domain by factorisation.
    nroots:
        Compute all roots using approximate numerical techniques.
    sympy.polys.polyroots.roots:
        Compute symbolic expressions for roots using radical formulae.

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Abel%E2%80%93Ruffini_theorem
    Fr  r  1Cannot compute real roots of %s, not a polynomialrU  rM  )rT   rS   r   r  r9   r8   rZ  r\   rU  rM  r   s       ra   rZ  rZ  /  sv    B	E5!!T"155?? "">??
 ;;8;<<	  E?!CE 	EEr  c                     	 t        | d      }t        | t               s!|j                  j                  st	        d      |j                  ||      S # t
        $ r t	        d| z        w xY w)a  
    Returns the real roots of ``f`` with multiplicities.

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

    Finds all real roots of a univariate polynomial with rational coefficients
    of any degree exactly. The roots are represented in the form given by
    :func:`~.rootof`. This is equivalent to using :func:`~.rootof` or
    :func:`~.all_roots` and filtering out only the real roots. However if only
    the real roots are needed then :func:`real_roots` is more efficient than
    :func:`~.all_roots` because it computes only the real roots and avoids
    costly complex root isolation routines.

    Examples
    ========

    >>> from sympy import real_roots
    >>> from sympy.abc import x, y

    >>> real_roots(2*x**3 - 7*x**2 + 4*x + 4)
    [-1/2, 2, 2]
    >>> real_roots(2*x**3 - 7*x**2 + 4*x + 4, multiple=False)
    [(-1/2, 1), (2, 2)]

    Real roots of any polynomial with rational coefficients of any degree can
    be represented using :py:class:`~.ComplexRootOf`:

    >>> p = x**9 + 2*x + 2
    >>> print(real_roots(p))
    [CRootOf(x**9 + 2*x + 2, 0)]
    >>> [r.evalf(3) for r in real_roots(p)]
    [-0.865]

    All rational roots will be returned as rational numbers. Roots of some
    simple factors will be expressed using radical or other formulae (unless
    ``radicals=False`` is passed). All other roots will be expressed as
    :class:`~.ComplexRootOf`.

    >>> p = (x + 7)*(x**2 - 2)*(x**3 + x + 1)
    >>> print(real_roots(p))
    [-7, -sqrt(2), CRootOf(x**3 + x + 1, 0), sqrt(2)]
    >>> print(real_roots(p, radicals=False))
    [-7, CRootOf(x**2 - 2, 0), CRootOf(x**3 + x + 1, 0), CRootOf(x**2 - 2, 1)]

    All returned root expressions will numerically evaluate to real numbers
    with no imaginary part. This is in contrast to the expressions generated by
    the cubic or quartic formulae as used by :func:`~.roots` which suffer from
    casus irreducibilis [1]_:

    >>> from sympy import roots
    >>> p = 2*x**3 - 9*x**2 - 6*x + 3
    >>> [r.evalf(5) for r in roots(p, multiple=True)]
    [5.0365 - 0.e-11*I, 0.33984 + 0.e-13*I, -0.87636 + 0.e-10*I]
    >>> [r.evalf(5) for r in real_roots(p, x)]
    [-0.87636, 0.33984, 5.0365]
    >>> [r.is_real for r in roots(p, multiple=True)]
    [None, None, None]
    >>> [r.is_real for r in real_roots(p)]
    [True, True, True]

    Using :func:`real_roots` is equivalent to using :func:`~.all_roots` (or
    :func:`~.rootof`) and filtering out only the real roots:

    >>> from sympy import all_roots
    >>> r = [r for r in all_roots(p) if r.is_real]
    >>> real_roots(p) == r
    True

    If only the real roots are wanted then using :func:`real_roots` is faster
    than using :func:`~.all_roots`. Using :func:`real_roots` avoids complex root
    isolation which can be a lot slower than real root isolation especially for
    polynomials of high degree which typically have many more complex roots
    than real roots.

    Irrational algebraic or transcendental coefficients cannot be handled by
    :func:`real_roots` (or :func:`~.rootof` more generally):

    >>> from sympy import sqrt, expand
    >>> p = expand((x - sqrt(2))*(x - sqrt(3)))
    >>> print(p)
    x**2 - sqrt(3)*x - sqrt(2)*x + sqrt(6)
    >>> real_roots(p)
    Traceback (most recent call last):
    ...
    NotImplementedError: sorted roots not supported over EX

    In the case of algebraic or transcendental coefficients
    :func:`~.ground_roots` might be able to find some roots by factorisation:

    >>> from sympy import ground_roots
    >>> ground_roots(p, x, extension=True)
    {sqrt(2): 1, sqrt(3): 1}

    If the coefficients are numeric then :func:`~.nroots` can be used to find
    all roots approximately:

    >>> from sympy import nroots
    >>> nroots(p, 5)
    [1.4142, 1.732]

    If the coefficients are symbolic then :func:`sympy.polys.polyroots.roots`
    or :func:`~.ground_roots` should be used instead.

    >>> from sympy import roots, ground_roots
    >>> p = x**2 - 3*x*y + 2*y**2
    >>> roots(p, x)
    {y: 1, 2*y: 1}
    >>> ground_roots(p, x)
    {y: 1, 2*y: 1}

    Parameters
    ==========

    f : :class:`~.Expr` or :class:`~.Poly`
        A univariate polynomial with rational (or ``Float``) coefficients.
    multiple : ``bool`` (default ``True``).
        Whether to return a ``list`` of roots or a list of root/multiplicity
        pairs.
    radicals : ``bool`` (default ``True``)
        Use simple radical formulae rather than :py:class:`~.ComplexRootOf` for
        some irrational roots.

    Returns
    =======

    A list of :class:`~.Expr` (usually :class:`~.ComplexRootOf`) representing
    the real roots is returned. The roots are arranged in increasing order and
    are repeated according to their multiplicities as roots of ``f``.

    If ``multiple=False`` is passed then a list of root/multiplicity pairs is
    returned instead.

    If ``radicals=False`` is passed then all roots will be represented as
    either rational numbers or :class:`~.ComplexRootOf`.

    See also
    ========

    Poly.real_roots:
        The underlying :class:`Poly` method used by :func:`real_roots`.
    rootof:
        Compute a single numbered root of a univariate polynomial.
    all_roots:
        Compute all real and non-real roots using :func:`~.rootof`.
    ground_roots:
        Compute some roots in the ground domain by factorisation.
    nroots:
        Compute all roots using approximate numerical techniques.
    sympy.polys.polyroots.roots:
        Compute symbolic expressions for roots using radical formulae.

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Casus_irreducibilis
    Fr  r  r	  r
  )rT   rS   r   r  r9   r8   rW  r  s       ra   rW  rW    sv    ~	E5!!T"155?? "">??
 <<H<==	  E?!CE 	EEr  c                     	 t        | d      }t        | t               s!|j                  j                  st	        d      |j                  |||      S # t
        $ r t	        d| z        w xY w)aL  
    Compute numerical approximations of roots of ``f``.

    Examples
    ========

    >>> from sympy import nroots
    >>> from sympy.abc import x

    >>> nroots(x**2 - 3, n=15)
    [-1.73205080756888, 1.73205080756888]
    >>> nroots(x**2 - 3, n=30)
    [-1.73205080756887729352744634151, 1.73205080756887729352744634151]

    Fr  r  z6Cannot compute numerical roots of %s, not a polynomial)r*  r_  r`  )rT   rS   r   r  r9   r8   rx  )r\   r*  r_  r`  r   s        ra   rx  rx  k  sw    "	J5!!T"155?? "">??
 88a(G8<<	  JDqHJ 	JJs   >A A,c                    t        j                  |g        	 t        | g|i |\  }}t        | t              s!|j
                  j                  st        d      |j                         S # t        $ r}t        dd|      d}~ww xY w)z
    Compute roots of ``f`` by factorization in the ground domain.

    Examples
    ========

    >>> from sympy import ground_roots
    >>> from sympy.abc import x

    >>> ground_roots(x**6 - 4*x**4 + 4*x**3 - x**2)
    {0: 2, 1: 2}

    r  r|  r   N)rl   rI  r'  rS   rT   r   r  r9   r<   r=   r|  rL  s         ra   r|  r|    s     $#81D1D13!T"155?? "">?? >>  83778s   AA+ +	B4BBc                 P   t        j                  |g        	 t        | g|i |\  }}t        | t              s!|j
                  j                  st        d      |j                  |      }|j                  s|j                         S |S # t        $ r}t        dd|      d}~ww xY w)a  
    Construct a polynomial with n-th powers of roots of ``f``.

    Examples
    ========

    >>> from sympy import nth_power_roots_poly, factor, roots
    >>> from sympy.abc import x

    >>> f = x**4 - x**2 + 1
    >>> g = factor(nth_power_roots_poly(f, 2))

    >>> g
    (x**2 - x + 1)**2

    >>> R_f = [ (r**2).expand() for r in roots(f) ]
    >>> R_g = roots(g).keys()

    >>> set(R_f) == set(R_g)
    True

    r  r  r   N)rl   rI  r'  rS   rT   r   r  r9   r<   r=   r  rO  rZ   )r\   r*  rV   r{   r   r|   r|  r_   s           ra   r  r    s    0 $#@1D1D13!T"155?? "">?? ##A&F99~~  @ 63??@s   AB
 
	B%B  B%)	_signsimpc                   ddl m} ddlm} t	        j
                  |dg       t        |       } |r ||       } i }d|v r|d   |d<   t        | t        t        f      sO| j                  s t        | t              st        | t              s| S t        | d      } | j                         \  }}nt        |       dk(  ry| \  }}t        |t               rCt        |t               r3|j"                  |d<   |j$                  |d	<   |j'                  dd      |d<   |j)                         |j)                         }}n)t        | t              rt        |       S t+        d
| z        ddlm 	 | j1                        r
t3                |||fg|i |\  }	\  }
}|	j4                  s9t        | t        t        f      s| j7                         S t8        j:                  ||fS 	 d|
jG                  |      c}\  }}|j'                  dd      rd|vr|	jZ                  |d<   t        | t        t        f      s$||j)                         |j)                         z  z  S |j)                         |j)                         }}|j'                  dd      s|||fS |t!        |g|i |t!        |g|i |fS # t2        $ rE}| j<                  r| j1                        st3        |      | j>                  s| j@                  rjtC        | jD                  fdd      \  }}|D cg c]  }tG        |       nc c}w }} | jH                  tG         | jH                  |       g| cY d}~S g }tK        |       }tM        |       |D ]Z  }t        |t        t        tN        f      r	 |jQ                  |tG        |      f       |jS                          M# tT        $ r Y Xw xY w | jW                  tY        |            cY d}~S d}~ww xY w)a[  
    Cancel common factors in a rational function ``f``.

    Examples
    ========

    >>> from sympy import cancel, sqrt, Symbol, together
    >>> from sympy.abc import x
    >>> A = Symbol('A', commutative=False)

    >>> cancel((2*x**2 - 2)/(x**2 - 2*x + 1))
    (2*x + 2)/(x - 1)
    >>> cancel((sqrt(3) + sqrt(15)*A)/(sqrt(2) + sqrt(10)*A))
    sqrt(6)/2

    Note: due to automatic distribution of Rationals, a sum divided by an integer
    will appear as a sum. To recover a rational form use `together` on the result:

    >>> cancel(x/2 + 1)
    x/2 + 1
    >>> together(_)
    (x + 2)/2
    r   )signsimp)sringrO  T)radicalr  rV   rP   zunexpected argument: %sr1  c                 H    | j                   du xr | j                         S r  )r  has)r  r2  s    ra   ri  zcancel.<locals>.<lambda>  s'      D(Ay1A-A rd   r  Nr   F).r  r  sympy.polys.ringsr  rl   rI  r"   rS   r7  r   rA  r   r	   r   r  r   rT   rV   rP   r  rZ   r  r4  r2  r  r9   ngensr)  r   r  r  r  r  rL   r{   r  r`   r$   rC  r&   r3  skiprn   r  rq   r   )r\   r  rV   r{   r  r  r|   r  rt  r  r   r   msgr   ncr   r;  poter  r  r2  s                        @ra   r  r    st   2 1'$	*
AQK
C$G}Ga%(;;*Q
3:a;NHD)!1	Q11a:a#6&&CKHHCM777D1CLyy{AIIK1	Au	A2Q677> *55!##1a&04040	6Aqwwa%0xxz!uua{"	 < 188A;IAv1
www6#4iiFa%(!))+aiik)**yy{AIIK1www&a7Nd1+t+s+T!-Bd-Bc-BBBI  *AEE)$4!#&&88qxx "BEAr &((&)((B(166&,2r22D$Q'CI a%!<=KKF1I/HHJ*  ::d4j))/*sb   $A J% J% %
O4/A"O/L$#0O/O49O/,O ?O/ 	O	O/OO/)O4/O4c                 Z   t        j                  |ddg       	 t        | gt        |      z   g|i |\  }}|j                  }d}|j                  r;|j                  r/|j                  s#|j                  d|j                         i      }d}dd	lm}	  |	|j                  |j                  |j                        \  }
}t!        |      D ]L  \  }}|j#                  |j                        j$                  j'                         }|
j)                  |      ||<   N |d   j+                  |d
d       \  }}|D cg c]!  }t,        j/                  t1        |      |      # }}t,        j/                  t1        |      |      }|r3	 |D cg c]  }|j3                          c}|j3                         }}||}}|j6                  s.|D cg c]  }|j9                          c}|j9                         fS ||fS # t        $ r}t        dd|      d}~ww xY wc c}w c c}w # t4        $ r Y qw xY wc c}w )a<  
    Reduces a polynomial ``f`` modulo a set of polynomials ``G``.

    Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``,
    computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r``
    such that ``f = q_1*g_1 + ... + q_n*g_n + r``, where ``r`` vanishes or ``r``
    is a completely reduced polynomial with respect to ``G``.

    Examples
    ========

    >>> from sympy import reduced
    >>> from sympy.abc import x, y

    >>> reduced(2*x**4 + y**2 - x**2 + y**3, [x**3 - x, y**3 - y])
    ([2*x, 1], x**2 + y**2 + y)

    rO  r  reducedr   NFrP   Txringr   )rl   rI  r/  rt   r<   r=   rP   r  r  r  r  r  r  r!  rV   ri   r   r   rg   r   r   r~  rT   rr   rq   r  r6   rO  rZ   )r\   r   rV   r{   rO  r|   r|  rP   r%  r!  _ringr   r   rD  r  ru  rt  _Q_rs                      ra   r  r  ;  s   ( $& 123,aS47]JTJTJ
s ZZFG
xxFNN6??ii6#3#3#567'SXXszz3995HE1U# )4szz*..668??4(a) 8<<ab	"DAq0121a#	&2A2Q%A	+,-aaiik-qyy{B rqA99%&'		'44!tC  3	1c223& 	3
 . 		 (sG   G1 7&HH HH H(1	H:HHH 	H%$H%c                      t        | g|i |S )a  
    Computes the reduced Groebner basis for a set of polynomials.

    Use the ``order`` argument to set the monomial ordering that will be
    used to compute the basis. Allowed orders are ``lex``, ``grlex`` and
    ``grevlex``. If no order is specified, it defaults to ``lex``.

    For more information on Groebner bases, see the references and the docstring
    of :func:`~.solve_poly_system`.

    Examples
    ========

    Example taken from [1].

    >>> from sympy import groebner
    >>> from sympy.abc import x, y

    >>> F = [x*y - 2*y, 2*y**2 - x**2]

    >>> groebner(F, x, y, order='lex')
    GroebnerBasis([x**2 - 2*y**2, x*y - 2*y, y**3 - 2*y], x, y,
                  domain='ZZ', order='lex')
    >>> groebner(F, x, y, order='grlex')
    GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y,
                  domain='ZZ', order='grlex')
    >>> groebner(F, x, y, order='grevlex')
    GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y,
                  domain='ZZ', order='grevlex')

    By default, an improved implementation of the Buchberger algorithm is
    used. Optionally, an implementation of the F5B algorithm can be used. The
    algorithm can be set using the ``method`` flag or with the
    :func:`sympy.polys.polyconfig.setup` function.

    >>> F = [x**2 - x - 1, (2*x - 1) * y - (x**10 - (1 - x)**10)]

    >>> groebner(F, x, y, method='buchberger')
    GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex')
    >>> groebner(F, x, y, method='f5b')
    GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex')

    References
    ==========

    1. [Buchberger01]_
    2. [Cox97]_

    )GroebnerBasisr   rV   r{   s      ra   r.   r.   w  s    f *T*T**rd   c                 4    t        | g|i |j                  S )a[  
    Checks if the ideal generated by a Groebner basis is zero-dimensional.

    The algorithm checks if the set of monomials not divisible by the
    leading monomial of any element of ``F`` is bounded.

    References
    ==========

    David A. Cox, John B. Little, Donal O'Shea. Ideals, Varieties and
    Algorithms, 3rd edition, p. 230

    )r&  is_zero_dimensionalr'  s      ra   r)  r)    s     *T*T*>>>rd   c                       e Zd ZdZd Zed        Zed        Zed        Z	ed        Z
ed        Zed        Zed	        Zd
 Zd Zd Zd Zd Zd Zed        Zd ZddZd Zy)r&  z%Represents a reduced Groebner basis. c                 "   t        j                  |ddg       	 t        |g|i |\  }}ddlm}  ||j                  |j                  |j                        }|D 	cg c].  }	|	s|j                  |	j                  j                               0 }}	t        |||j                        }
|
D cg c]  }t         j#                  ||       }
}| j%                  |
|      S # t        $ r}t	        dt        |      |      d}~ww xY wc c}	w c c}w )z>Compute a reduced Groebner basis for a system of polynomials. rO  r  r.   Nr   )PolyRingr  )rl   rI  r/  r<   r=   r   r  r,  rV   rP   ri   r   rg   r   	_groebnerr  rT   rr   _new)rz   r   rV   r{   rO  r|   r|  r,  ringrD  r   r]   s               ra   r}   zGroebnerBasis.__new__  s    dWh$78	=0BTBTBJE3 	/#**cii8@EN 0 0 23NNeT#**5./0T__Q$00xx3 " 	=#JA<<	= O 1s)   C  D&+D/D 	D)C??Dc                 ^    t        j                  |       }t        |      |_        ||_        |S r   )r   r}   r7  _basis_options)rz   basisrl   r   s       ra   r.  zGroebnerBasis._new  s'    mmC 5\

rd   c                 p    d | j                   D        }t        | t        | j                  j                   fS )Nc              3   <   K   | ]  }|j                           y wr   r  )rt  r  s     ra   ru  z%GroebnerBasis.args.<locals>.<genexpr>  s     22s   )r1  r   r2  rV   )r   r3  s     ra   r{   zGroebnerBasis.args  s.    2dkk2uudmm&8&89::rd   c                 \    | j                   D cg c]  }|j                          c}S c c}w r   )r1  rZ   r   rD  s     ra   r.  zGroebnerBasis.exprs  s     +/;;74777s   )c                 ,    t        | j                        S r   )rt   r1  r   s    ra   rO  zGroebnerBasis.polys  s    DKK  rd   c                 .    | j                   j                  S r   )r2  rV   r   s    ra   rV   zGroebnerBasis.gens  s    }}!!!rd   c                 .    | j                   j                  S r   )r2  rP   r   s    ra   rP   zGroebnerBasis.domain  s    }}###rd   c                 .    | j                   j                  S r   )r2  ri   r   s    ra   ri   zGroebnerBasis.order  s    }}"""rd   c                 ,    t        | j                        S r   )r   r1  r   s    ra   __len__zGroebnerBasis.__len__  s    4;;rd   c                     | j                   j                  rt        | j                        S t        | j                        S r   )r2  rO  iterr.  r   s    ra   r  zGroebnerBasis.__iter__  s-    ==

##

##rd   c                 r    | j                   j                  r| j                  }||   S | j                  }||   S r   )r2  rO  r.  )r   itemr3  s      ra   __getitem__zGroebnerBasis.__getitem__  s9    ==JJE T{ JJET{rd   c                 r    t        | j                  t        | j                  j	                               f      S r   )hashr1  r7  r2  r   r   s    ra   r   zGroebnerBasis.__hash__	  s(    T[[%(;(;(=">?@@rd   c                    t        || j                        r4| j                  |j                  k(  xr | j                  |j                  k(  S t	        |      r2| j
                  t        |      k(  xs | j                  t        |      k(  S y)NF)rS   r   r1  r2  rK   rO  rt   r.  r   r  s     ra   r  zGroebnerBasis.__eq__  sd    eT^^,;;%,,.R4==ENN3RRe_::e,I

d5k0IIrd   c                     | |k(   S r   r  rF  s     ra   r  zGroebnerBasis.__ne__  s    5=  rd   c                     d }t        dgt        | j                        z        }| j                  j                  }| j
                  D ]"  }|j                  |      } ||      s||z  }$ t        |      S )a{  
        Checks if the ideal generated by a Groebner basis is zero-dimensional.

        The algorithm checks if the set of monomials not divisible by the
        leading monomial of any element of ``F`` is bounded.

        References
        ==========

        David A. Cox, John B. Little, Donal O'Shea. Ideals, Varieties and
        Algorithms, 3rd edition, p. 230

        c                 :    t        t        t        |             dk(  S r   )sumr   r6  )monomials    ra   
single_varz5GroebnerBasis.is_zero_dimensional.<locals>.single_var&  s    s4*+q00rd   r   r,  )r/   r   rV   r2  ri   rO  r  r  )r   rL  r  ri   rD  rK  s         ra   r)  z!GroebnerBasis.is_zero_dimensional  sr    	1 aSTYY/0	##JJ 	&DwwUw+H(#X%			& 9~rd   c                     | j                   }|j                  }t        |      }||k(  r| S | j                  st	        d      t        | j                        }|j                  }|j                  |j                         |d      }ddl
m}  ||j                  |j                  |      \  }}	t        |      D ]L  \  }
}|j                  |j                        j                  j!                         }|j#                  |      ||
<   N t%        |||      }|D cg c]!  }t&        j)                  t+        |      |      # }}|j,                  s)|D cg c]  }|j/                  d      d    }}||_        | j1                  ||      S c c}w c c}w )a  
        Convert a Groebner basis from one ordering to another.

        The FGLM algorithm converts reduced Groebner bases of zero-dimensional
        ideals from one ordering to another. This method is often used when it
        is infeasible to compute a Groebner basis with respect to a particular
        ordering directly.

        Examples
        ========

        >>> from sympy.abc import x, y
        >>> from sympy import groebner

        >>> F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1]
        >>> G = groebner(F, x, y, order='grlex')

        >>> list(G.fglm('lex'))
        [2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7]
        >>> list(groebner(F, x, y, order='lex'))
        [2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7]

        References
        ==========

        .. [1] J.C. Faugere, P. Gianni, D. Lazard, T. Mora (1994). Efficient
               Computation of Zero-dimensional Groebner Bases by Change of
               Ordering

        z?Cannot convert Groebner bases of ideals with positive dimension)rP   ri   r   r   Tr  r   )r2  ri   r0   r)  rn   rt   r1  rP   r  r  r  r!  rV   r   r   rg   r   r   r-   rT   rr   rq   r  r  r.  )r   ri   r|   	src_order	dst_orderrO  rP   r!  r"  r   r   rD  r   r]   s                 ra   fglmzGroebnerBasis.fglm7  sc   > mmII	 '		!K''%&ghhT[[!ii&&(
 
 	,3::y9q ' 	-GAt??3::.22::<Dt,E!H	- ui0456qT__T!Wc*66:;<Q-a0<A<CJyyC   7 =s   &FFc                 $   t         j                  || j                        }|gt        | j                        z   }| j                  }|j
                  }d}|r;|j                  r/|j                  s#|j                  d|j                         i      }d}ddl
m}  ||j                  |j
                  |j                        \  }	}
t        |      D ]L  \  }}|j                  |j
                        j                   j#                         }|	j%                  |      ||<   N |d   j'                  |dd       \  }}|D cg c]!  }t         j)                  t+        |      |      # }}t         j)                  t+        |      |      }|r3	 |D cg c]  }|j-                          c}|j-                         }}||}}|j0                  s.|D cg c]  }|j3                          c}|j3                         fS ||fS c c}w c c}w # t.        $ r Y Sw xY wc c}w )a#  
        Reduces a polynomial modulo a Groebner basis.

        Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``,
        computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r``
        such that ``f = q_1*f_1 + ... + q_n*f_n + r``, where ``r`` vanishes or ``r``
        is a completely reduced polynomial with respect to ``G``.

        Examples
        ========

        >>> from sympy import groebner, expand
        >>> from sympy.abc import x, y

        >>> f = 2*x**4 - x**2 + y**3 + y**2
        >>> G = groebner([x**3 - x, y**3 - y])

        >>> G.reduce(f)
        ([2*x, 1], x**2 + y**2 + y)
        >>> Q, r = _

        >>> expand(sum(q*g for q, g in zip(Q, G)) + r)
        2*x**4 - x**2 + y**3 + y**2
        >>> _ == f
        True

        FrP   Tr   r   r   N)rT   rx   r2  rt   r1  rP   r  r  r  r  r  r!  rV   ri   r   r   rg   r   r   r~  rr   rq   r  r6   rO  rZ   )r   r   r  rD  rO  r|   rP   r%  r!  r"  r   r   r  ru  rt  r#  r$  s                    ra   r   zGroebnerBasis.reducey  s   8 tT]]3dkk**mmFNN6??))Xv'7'7'9:;CG+3::syy9q ' 	-GAt??3::.22::<Dt,E!H	- Qx||E!"I&1456qT__T!Wc*66OODGS)/01!!))+1199;B 21yy)*+AAIIK+QYY[88a4K 7
 2!  ,s0   :&G4G> G9G> H9G> >	H
	H
c                 0    | j                  |      d   dk(  S )am  
        Check if ``poly`` belongs the ideal generated by ``self``.

        Examples
        ========

        >>> from sympy import groebner
        >>> from sympy.abc import x, y

        >>> f = 2*x**3 + y**3 + 3*y
        >>> G = groebner([x**2 + y**2 - 1, x*y - 2])

        >>> G.contains(f)
        True
        >>> G.contains(f + 1)
        False

        r   r   )r   r7  s     ra   containszGroebnerBasis.contains  s    & {{4 #q((rd   Nr
  )r[   r  r  r  r}   r  r.  r  r{   r.  rO  rV   rP   ri   r=  r  rB  r   r  r  r)  rP  r   rS  r  rd   ra   r&  r&    s    / &   ; ; 8 8 ! ! " " $ $ # # $A!  >@!D?B)rd   r&  c                     t        j                  g        fdt        |       } | j                  rt	        | g|i S dvrdd<   t        j
                  |      } | |      S )z
    Efficiently transform an expression into a polynomial.

    Examples
    ========

    >>> from sympy import poly
    >>> from sympy.abc import x

    >>> poly(x*(x**2 + x - 1)**2)
    Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ')

    c                 6   g g }}t        j                  |       D ]`  }g g }}t        j                  |      D ]  }|j                  r|j	                   
||             (|j
                  rw|j                  j                  ra|j                  j                  rK|j                  dk\  r<|j	                   
|j                  |      j                  |j                               |j	                  |        |s|j	                  |       |d   }|dd  D ]  }|j                  |      } |r?t        | }|j                  r||z  }n%|j                  t        j                  ||            }|j	                  |       c |st        j                  | |      }	na|d   }	|dd  D ]  }|	j                  |      }	 |r?t        | }|j                  r|	|z  }	n%|	j                  t        j                  ||            }	 |	j                  |j!                  dd      i S )Nr   r   rV   r  )r
   r  r   r  r3  r  r  r  r~  rp  r   rA  rT   rx   r  r   r  )r   r|   r  
poly_termsr  r  poly_factorsr{  productr_   _polyr{   s             ra   rY  zpoly.<locals>._poly  s   zMM$' 	+D$&\G--- +== ''fc(:;]]v{{'9'9

--&**/ ''fkk3/33FJJ?A NN6*+  T"&q/*12. 2F%kk&1G2  ']F''6)")++doofc.J"K!!'*;	+> __T3/F]F"12 *D)* E{>>dNF#ZZc(BCFv~~swwvr2;d;;rd   r)  F)rl   rI  r"   rv   rT   rm   )r   rV   r{   r|   rY  s     ` @ra   rD  rD    sr     $#2<h 4=D||D(4(4((tX


d
+Csrd   c                 :   | dk  rt        d|d|       |d   |dd }}|t        |d      \  }}t         |t        |       g|| |      }| t        j                  |t        d            }nt        j                  ||      }|r|S |j                         S )	a  Common interface to the low-level polynomial generating functions
    in orthopolys and appellseqs.

    Parameters
    ==========

    n : int
        Index of the polynomial, which may or may not equal its degree.
    f : callable
        Low-level generating function to use.
    K : Domain or None
        Domain in which to perform the computations. If None, use the smallest
        field containing the rationals and the extra parameters of x (see below).
    name : str
        Name of an arbitrary individual polynomial in the sequence generated
        by f, only used in the error message for invalid n.
    x : seq
        The first element of this argument is the main variable of all
        polynomials in this sequence. Any further elements are extra
        parameters required by f.
    polys : bool, optional
        If True, return a Poly, otherwise (default) return an expression.
    r   zCannot generate z
 of index r   NT)r   r  )	r  r(   r1   r(  r  r   r    rT   rZ   )	r*  r\   Kr  r  rO  headtailrD  s	            ra   
named_polyr^  "  s    0 	1uT1EFF1qu$Dy"4t44qQ"$""A&D|||D%*-xxd#4,dlln,rd   r  r   )FNNNFFFr  r	  r?  r  )r  	functoolsr   r   operatorr   typingr   
sympy.corer   r	   r
   r   sympy.core.basicr   sympy.core.decoratorsr   sympy.core.exprtoolsr   r   r   sympy.core.evalfr   r   r   r   r   sympy.core.functionr   sympy.core.mulr   r   sympy.core.intfuncr   sympy.core.numbersr   r   r   sympy.core.relationalr   r   sympy.core.sortingr   sympy.core.symbolr    r!   sympy.core.sympifyr"   r#   sympy.core.traversalr$   r%   sympy.logic.boolalgr&   sympy.polysr'   rl   sympy.polys.constructorr(   sympy.polys.domainsr)   r*   r+   !sympy.polys.domains.domainelementr,   sympy.polys.fglmtoolsr-   sympy.polys.groebnertoolsr.   r-  sympy.polys.monomialsr/   sympy.polys.orderingsr0   sympy.polys.polyclassesr1   r2   r3   sympy.polys.polyerrorsr4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   sympy.polys.polyutilsr?   r@   rA   rB   rC   rD   sympy.polys.rationaltoolsrE   sympy.polys.rootisolationrF   sympy.utilitiesrG   rH   rI   sympy.utilities.exceptionsrJ   sympy.utilities.iterablesrK   rL   rN  ro  mpmath.libmp.libhyperrM   rc   rT   r  r'  r&  r/  r-  r?  r  r  r  r  r  r  rs  rw  ry  r{  r~  r  r  r  r  r  r  r  r  r  r  r  r  r  r  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#  r9  rJ  rZ  rW  rx  r|  r  r  r  r)  r&  rD  r^  r  rd   ra   <module>r     s   > $    # , A AM M * + # 7 7 6 & + 0 > + . 4 * * ; - ; * . 1 1	 	 	 	  / A 5 5 @ 4   /!J |B`5 |B` |B`~E Zt Z Zz & &%P 0 0[| 7N 7Nt 1 1h ( (4 ! !0  2 ! !2  :  :  D  D  >  >  >  D # #L # #L 0 0f  : &+ ! !H  : % %P Q Qh 0 0f J JZ / /d r3 r3j  :  :  0 * *Z  :  :  : + +\ < <
    F  :$ 6
7t)FX8|~)X = =" 8 8" @ @"  _ _D 4 4n U U8 + +@ K= K=\ i> i>X = =<  : ( (V # cC cCL 8 8v 2+ 2+j ? ?" M)E M) M)` N Nb"-rd   