
    MZd                       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!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.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z7 ddl8m9Z9 ddl:m;Z;m<Z<m=Z= ddl>m?Z? ddl@mAZA ddlBmCZD ddlEmFZF ddlGmHZH ddlImJZJmKZKmLZL ddlMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZX ddlYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_ ddl`maZa ddlbmcZc dd ldmeZemfZfmgZg dd!lhmiZi dd"ljmkZkmlZl dd#l5Zmdd#lnZndd$lompZp d% Zqef G d& d'e             Zref G d( d)er             Zsefd*        Ztd+ Zuefd,        Zvd- Zwd. Zxefdtd/       Zyefd0        Zzefd1        Z{efd2        Z|efd3        Z}efd4        Z~efd5        Zefd6        Zefd7        Zefd8        Zefd9        Zefd:        Zefd;        Zefd<        Zefd=        Zefd>        Zefd?        Zefd@        ZefdAdBdC       ZefdD        ZefdE        ZefdF        ZefdudG       ZefdH        ZefdudI       ZefdJ        ZefdK        ZefdL        ZefdM        ZefdN        ZefdO        ZefdP        ZefdQ        ZefdR        ZefdS        ZefdT        ZefdU        ZdV ZdW ZdX ZdY ZdZ Zd[ Zd\ Zd] Zefd^        Zefd_        Zefd`        ZefdAdadb       Zefdvdc       Zefdwdd       Zefdxde       Zefdydg       Zefdzdh       Zefdi        Zefdj        Zefdfdkdl       Zefdm        Zefdn        ZCefdo        Zef G dp dqe             Zefdr        Zds 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              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)Na@  
                        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gensr9   	is_MatrixNotImplementedgetattras_expr__name__rJ   )fgexpr_methodresultfuncs       7/usr/lib/python3/dist-packages/sympy/polys/polytools.pywrapperz_polifyit.<locals>.wrapperD   s    QKa1:4 "AKK+AFF+& Aqz!!!) # ;;))%aiik4==A$Q/- 273^	 !s   A# #C ACC)r   )r_   ra   s   ` r`   	_polifyitrb   C   s     
4[" "8 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~ 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 )rS   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

    reprU   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        |      }|j                   r| j#                  ||      S | j%                  ||      S )z:Create a new polynomial instance out of something useful. orderz&'order' keyword is not implemented yet)exclude)optionsbuild_optionsNotImplementedErrorrR   r1   r2   r3   r,   _from_domain_elementrK   strdict
_from_dict
_from_listlistr"   is_Poly
_from_poly
_from_exprclsrf   rU   argsopts        r`   __new__zPoly.__new__   s    ##D$/c>%&NOOcCc=9:++C55c3'#t$~~c3//~~d3i55#,C{{~~c3//~~c3//rc   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, )	rR   r1   r9   levlenr   rz   rf   rU   )rw   rf   rU   objs       r`   newzPoly.new   sh     #s#!7#=? ?WWD	A%!d"KLLmmC 
rc   c                 ^    t        | j                  j                         g| j                   S N)r?   rf   to_sympy_dictrU   selfs    r`   exprz	Poly.expr   s#    txx557D$))DDrc   c                 6    | j                   f| j                  z   S r   )r   rU   r   s    r`   rx   z	Poly.args   s    		|dii''rc   c                 6    | j                   f| j                  z   S r   re   r   s    r`   _hashable_contentzPoly._hashable_content   s    {TYY&&rc   c                 R    t        j                  ||      }| j                  ||      S )(Construct a polynomial from a ``dict``. )rj   rk   rp   rv   s        r`   	from_dictzPoly.from_dict   '     ##D$/~~c3''rc   c                 R    t        j                  ||      }| j                  ||      S )(Construct a polynomial from a ``list``. )rj   rk   rq   rv   s        r`   	from_listzPoly.from_list   r   rc   c                 R    t        j                  ||      }| j                  ||      S )*Construct a polynomial from a polynomial. )rj   rk   rt   rv   s        r`   	from_polyzPoly.from_poly   r   rc   c                 R    t        j                  ||      }| j                  ||      S +Construct a polynomial from an expression. )rj   rk   ru   rv   s        r`   rT   zPoly.from_expr   r   rc   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|   ry   )
rU   r8   r~   domainr(   itemsconvertr   r1   r   )rw   rf   ry   rU   levelr   monomcoeffs           r`   rp   zPoly._from_dict   s     xx"BD D D	A>*3C8KFC #		 3u#^^E2E
3 swws}}S%8@4@@rc   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   )rU   r8   r~   r:   r   r(   rr   mapr   r   r1   r   )rw   rf   ry   rU   r   r   s         r`   rq   zPoly._from_list  s     xx"BD DY!^-57 7 D	A>*3C8KFCs6>>3/0Cswws}}S%8@4@@rc   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   r   T)	__class__r   rf   rU   fieldr   setru   rY   reorder
set_domainto_field)rw   rf   ry   rU   r   r   s         r`   rt   zPoly._from_poly  s     #--#''#''-CHH-Cxx		CHH$388}D	)~~ckkmS99!ckk4(s?v..(C 
 d],,.C
rc   c                 D    t        ||      \  }}| j                  ||      S r   )rC   rp   )rw   rf   ry   s      r`   ru   zPoly._from_expr4  s%     #3,S~~c3''rc   c                     |j                   }|j                  }t        |      dz
  }|j                  |      g} | j                  t        j                  |||      g| S Nr|   )rU   r   r~   r   r   r1   r   )rw   rf   ry   rU   r   r   s         r`   rm   zPoly._from_domain_element:  sU    xxD	A~~c"#swws}}S%8@4@@rc   c                      t         |          S r   super__hash__r   r   s    r`   r   zPoly.__hash__D      w!!rc   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   rU   ranger~   monomsfree_symbolsfree_symbols_in_domain)r   symbolsrU   ir   s        r`   r   zPoly.free_symbolsG  sr    * %yys4y! 	A 8tAw333G	 4444rc   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}

        )rf   domr   is_Compositer   r   is_EXcoeffs)r   r   r   genr   s        r`   r   zPoly.free_symbols_in_domainf  s    & ((,,~~ ,3+++, 	 \\ .5---. rc   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   rU   r   s    r`   r   zPoly.gen  s     yy|rc   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    r`   r   zPoly.domain  s    *   rc   c                      | j                   | j                  j                  | j                  j                  | j                  j                        g| j
                   S )z3Return zero polynomial with ``self``'s properties. )r   rf   zeror}   r   rU   r   s    r`   r   z	Poly.zero  =     txxdhhllDHHLLANDIINNrc   c                      | j                   | j                  j                  | j                  j                  | j                  j                        g| j
                   S )z2Return one polynomial with ``self``'s properties. )r   rf   oner}   r   rU   r   s    r`   r   zPoly.one  s=     txxTXX\\488<<@M499MMrc   c                      | j                   | j                  j                  | j                  j                  | j                  j                        g| j
                   S )z3Return unit polynomial with ``self``'s properties. )r   rf   unitr}   r   rU   r   s    r`   r   z	Poly.unit  r   rc   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         r`   unifyz
Poly.unify  s+    2 xx{311vs1v~rc   c           
      6   t        |      }|j                  sk	 | 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        t#        t%        t'        ||                  ||      }n| j                  j!                  |      }|j                  |k7  rt        |j                  j                         |j                  |      \  }	}
|j                  j                  |k7  r3|
D cg c](  }|j!                  ||j                  j                        * }
}t        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   rf   r   rU   removerw   s       r`   r   zPoly._unify.<locals>.per  L    !GV}tFQJK'88<<,,3773&&&rc   )r"   rs   rf   r   r   
from_sympyr6   r7   rR   r1   rA   rU   r   r~   rB   to_dictr   ro   rr   zipr   )r[   r\   rU   r   r}   f_monomsf_coeffscr   g_monomsg_coeffsr   r   rw   s                @r`   r   zPoly._unify  sI   AJyyLuuyy!%%		!%%)):N:Nq:Q0RRR aeeS!j&<qvvqvv.Duuyyquuyy$7TQCvv~%2EEMMOQVVT&3"( 5599#CKLaAquuyy 9LHLT#h"9:;S#FEEMM#&vv~%2EEMMOQVVT&3"( 5599#CKLaAquuyy 9LHLT#h"9:;S#FEEMM#&#A$FGGkk4 	' CA~W " L'Q(JKKL  M  Ms   A)K3  -L-L3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|   )rU   rf   r   r   r   r   )r[   rf   rU   r   s       r`   r   zPoly.per
  si    $ <66D=4
#44Duuyy))#..q{{s*T**rc   c                     t        j                  | j                  d|i      }| j                  | j                  j                  |j                              S )z Set the ground domain of ``f``. r   )rj   rk   rU   r   rf   r   r   )r[   r   ry   s      r`   r   zPoly.set_domain'  s=    ##AFFXv,>?uuQUU]]3::.//rc   c                 .    | j                   j                  S )z Get the ground domain of ``f``. )rf   r   r[   s    r`   r   zPoly.get_domain,  s    uuyyrc   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)

        )rj   Modulus
preprocessr   r)   )r[   moduluss     r`   set_moduluszPoly.set_modulus0  s+     //,,W5||BwK((rc   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[   r   s     r`   get_moduluszPoly.get_modulusA  s8       600233!"HIIrc   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`. )rU   	is_numberevalreplacer9   rY   subs)r[   oldr   s      r`   
_eval_subszPoly._eval_subsV  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   )rf   ri   	enumeraterU   r   )r[   Jr   jr   rU   s         r`   ri   zPoly.excludec  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   rU   r   r   r   rr   indexr   rf   )r[   xy_ignorer   rU   s         r`   r   zPoly.replacev  s     9uua1%>@ @ 6Qaff_H;1AFF?,,.C##q';AFF|&'TZZ]#uuQUUu..1aKLLrc   c                 B     | j                         j                  |i |S )z-Match expression from Poly. See Basic.match())rY   match)r[   rx   kwargss      r`   r  z
Poly.match  s      qyy{  $1&11rc   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                  j                  t        |      dz
        |      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   )rj   Optionsr@   rU   r   r9   ro   rr   r   rB   rf   r   r   r1   r   r~   )r[   rU   rx   ry   rf   s        r`   r   zPoly.reorder  s     oob$'aff#.D[CI%!IK K 4]155==?AFFDIJKLuuSaeeiiTQ7duCCrc   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   rU   r   r1   r   r~   rf   r   )r[   r   rf   r   termsr   r   rU   s           r`   ltrimz
Poly.ltrim  s    & iiti$OOC IIK 	%LE55!9~%&;a&?@@$E%)	% vvabzquuS]]5#d)a-CKdKKrc   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   rU   r   add
ValueErrorr>   r   r   )r[   rU   indicesr   r   r   r   elts           r`   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)hasattrrf   r  r4   r   r[   r^   s     r`   r  zPoly.to_ring  s<     155)$UU]]_F'955uuV}rc   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  rf   r   r4   r   r  s     r`   r   zPoly.to_field  =     155*%UU^^%F':66uuV}rc   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  rf   r  r4   r   r  s     r`   r  zPoly.to_exact'  r  rc   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r   )r(   r  r   r   r   rU   )r[   r   r   rf   s       r`   retractzPoly.retract<  sM    ( $AII4I$8188#8#8#@DBS{{3s{33rc   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  rf   r#  r4   r   )r[   r   mnr   r^   s         r`   r#  z
Poly.sliceT  sr    9A!qA"A1vs1v1155'"UU[[Aq)F'733uuV}rc   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

        rh   )rf   r   r   r   )r[   rh   r   s      r`   r   zPoly.coeffsd  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(  )rf   r   r[   rh   s     r`   r   zPoly.monomsz  s    $ uu||%|((rc   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(  )rf   r  r   r   )r[   rh   r%  r   s       r`   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]

        )rf   
all_coeffsr   r   )r[   r   s     r`   r-  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

        )rf   
all_monomsr   s    r`   r/  zPoly.all_monoms  s    $ uu!!rc   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)]

        )rf   	all_termsr   r   )r[   r%  r   s      r`   r1  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  rR   tupler9   r   rU   )r[   r_   rU   rx   r  r   r   r^   s           r`   termwisezPoly.termwise  s    $ GGI 	CLE5%'F&%(%u%#(E%L)9EAC C	C q{{5<DNAFF<t<<rc   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    r`   lengthzPoly.length  s     199;rc   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  )rf   r   r   )r[   r  r   s      r`   r  zPoly.as_dict  s4     55==d=++55&&D&11rc   c                 n    |r| j                   j                         S | j                   j                         S )z%Switch to a ``list`` representation. )rf   to_listto_sympy_list)r[   r  s     r`   as_listzPoly.as_list  s(    55==?"55&&((rc   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~   rR   ro   rr   rU   r   r   r  r>   r?   rf   r   )r[   rU   mappingr   valuer   s         r`   rY   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)rS   rs   r9   )r   rU   rx   polys       r`   as_polyzPoly.as_polyK  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  rf   rC  r4   r   r  s     r`   rC  z	Poly.lifte  s<     155&!UUZZ\F'622uuV}rc   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  rf   rE  r4   r   r[   r   r^   s      r`   rE  zPoly.deflatez  sE     155)$IAv'955!%%-rc   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)rf   r   is_Numericalrs   r5   r  rH  r4   r   rU   r   )r[   rJ  r   r^   rU   s        r`   rH  zPoly.inject  s    $ eeiiH@3FGG155(#UU\\\.F'844;;'D66CKK'DquuV#d##rc   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ejectrI  )rf   r   rK  r5   r~   rU   rl   rH  r  rM  r4   r   )r[   rU   r   k_gensrJ  r^   s          r`   rM  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$$rc   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  rf   rQ  r4   r   rF  s      r`   rQ  zPoly.terms_gcd  sF     155+&)IAv';77!%%-rc   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  rf   rS  r4   r   r[   r   r^   s      r`   rS  zPoly.add_ground  A     155,'UU%%e,F'<88uuV}rc   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  rf   rW  r4   r   rT  s      r`   rW  zPoly.sub_ground  rU  rc   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  rf   rY  r4   r   rT  s      r`   rY  zPoly.mul_ground  rU  rc   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  rf   r[  r4   r   rT  s      r`   r[  zPoly.quo_ground2  sA    " 155,'UU%%e,F'<88uuV}rc   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  rf   r]  r4   r   rT  s      r`   r]  zPoly.exquo_groundJ  sA    & 155.)UU''.F'>::uuV}rc   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  rf   r_  r4   r   r  s     r`   r_  zPoly.absd  s<     155% UUYY[F'511uuV}rc   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  rf   ra  r4   r   r  s     r`   ra  zPoly.negy  <    " 155% UUYY[F'511uuV}rc   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"   rs   rS  r   r  rf   r  r4   r[   r\   r   r   r   r   r^   s          r`   r  zPoly.add  i    " AJyy<<?"xx{31155% UU1XF'5116{rc   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"   rs   rW  r   r  rf   rg  r4   rd  s          r`   rg  zPoly.sub  re  rc   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"   rs   rY  r   r  rf   r   r4   rd  s          r`   r   zPoly.mul  re  rc   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  rf   rj  r4   r   r  s     r`   rj  zPoly.sqr  rb  rc   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  rf   rl  r4   r   r[   r&  r^   s      r`   rl  zPoly.pow  sG    " F155% UUYYq\F'511uuV}rc   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  rf   ro  r4   )r[   r\   r   r   r   r   qrs           r`   ro  z	Poly.pdiv   sW     xx{31155&!66!9DAq'6221vs1v~rc   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  rf   rs  r4   rd  s          r`   rs  z	Poly.prem7  sK    < xx{31155&!VVAYF'6226{rc   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  rf   ru  r4   rd  s          r`   ru  z	Poly.pquo^  sK    & xx{31155&!VVAYF'6226{rc   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  rf   rw  r;   r   rY   r4   )r[   r\   r   r   r   r   r^   excs           r`   rw  zPoly.pexquoz  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  rf   rz  r4   r  r6   )r[   r\   autor   r   r   r   r!  rp  rq  QRs               r`   rz  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  rf   r  r4   r  r6   )	r[   r\   r}  r   r   r   r   r!  rq  s	            r`   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  rf   r  r4   r  r6   )	r[   r\   r}  r   r   r   r   r!  rp  s	            r`   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  rf   r  r;   r   rY   r4   r  r6   )
r[   r\   r}  r   r   r   r   r!  rp  rx  s
             r`   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)rR   r$  r~   rU   r9   r   r"   r  )r[   r   r6  s      r`   r	  zPoly._gen_to_level4  s    c3[Fw#&&7!C<'J%'-vs'< = =@vv||GCL11 @%83>@ @@s   #A: :Bc                     | j                  |      }t        | j                  d      r| j                  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

        degree)r	  r  rf   r  r4   )r[   r   r   s      r`   r  zPoly.degreeH  s?    ( OOC 155(#55<<?"'844rc   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  rf   r  r4   r   s    r`   r  zPoly.degree_listc  s2     155-(55$$&&'=99rc   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  rf   r  r4   r   s    r`   r  zPoly.total_degreev  s2      155.)55%%'''>::rc   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)rR   r!   	TypeErrortyperU   r   r~   r  rf   r   r  r4   )r[   sr   rU   s       r`   r  zPoly.homogenize  s    , !V$9DGCDD;QA66DAFFA66QD=D155,'55))!,4588#A':;;rc   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  rf   r  r4   r   s    r`   r  zPoly.homogeneous_order  s4    ( 155-.55**,,'+>??rc   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  rf   r  r4   r   r   )r[   rh   r^   s      r`   r  zPoly.LC  s`     88E?1%%155$UUXXZF'400uuyy!!&))rc   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  rf   r  r4   r   r   r  s     r`   r  zPoly.TC  sG     155$UUXXZF'400uuyy!!&))rc   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  rf   r   r4   r*  s     r`   r  zPoly.EC  s2     155(#88E?2&&'400rc   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/   rU   	exponents)r[   r   s     r`   coeff_monomialzPoly.coeff_monomial  s'    F quuhuaff-7788rc   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  rf   r~   rU   r  r  rr   r   r$  r4   r   r   )r[   Nr^   s      r`   r  zPoly.nth+  sw    2 155% 1vQVV$ !OPPQUUYYSa[ 12F'511uuyy!!&))rc   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.rl   )r[   r   r&  rights       r`   r   z
Poly.coeffM  s     "01 	1rc   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   rU   r*  s     r`   LMzPoly.LMY  s"    $ *AFF33rc   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     r`   EMzPoly.EMm  s"     +QVV44rc   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/   rU   r[   rh   r   r   s       r`   LTzPoly.LT}  s0    $ wwu~a(uqvv&--rc   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       r`   ETzPoly.ET  s0     wwu~b)uqvv&--rc   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  rf   r  r4   r   r   r  s     r`   r  zPoly.max_norm  sH     155*%UU^^%F':66uuyy!!&))rc   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  rf   r  r4   r   r   r  s     r`   r  zPoly.l1_norm  G     155)$UU]]_F'955uuyy!!&))rc   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)rf   r   r|  r   Oner   has_assoc_Ringget_ringr  r  r4   r   r   r  )r   r   r[   r   r   r^   s         r`   r  zPoly.clear_denoms  s    $ uuyy!!55!8Olln%%))$$&C155.)EE..0ME6'>::<<&fqc00!8O!))+%%rc   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  rY  )r   r\   r[   r   r   abs          r`   rat_clear_denomszPoly.rat_clear_denoms  s    * !S!QFF!3!3a4K~~d~+1~~d~+1LLOLLO!trc   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%  )getrf   r   r{  r   r  r   r  rR   r3  r$  r	  r4   )r   specsrx   r[   rf   specr   r%  s           r`   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7rc   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')

        evaluateTdiffr|   r  )r  r   r  rf   r   r  rR   r3  r$  r	  r4   )r[   r  r  rf   r  r   r%  s          r`   r  z	Poly.diffC	  s    " zz*d+a2%2622155&!uuQUUZZ!Z_--%%C =dE*!FC!1Chhs1vqs';<= 55:'622rc   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   )rR   ro   r   r   r3  rr   r~   rU   r  r   r	  r  rf   r4   r6   r5   r   r(   r   unify_with_symbolsr   r   r   )r   r   r  r}  r[   r=  r   r>  valuesr   r^   a_domain
new_domains                r`   r   z	Poly.evalk	  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     r`   __call__zPoly.__call__	  s    ( vvf~rc   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  rf   r  r4   )	r[   r\   r}  r   r   r   r   r  hs	            r`   r  zPoly.half_gcdex	  su    & !S!QCKK::<qA155,'<<?DAq'<881vs1v~rc   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  rf   r  r4   )
r[   r\   r}  r   r   r   r   r  tr  s
             r`   r  z
Poly.gcdex	  s~    * !S!QCKK::<qA155'"ggajGAq!'7331vs1vs1v%%rc   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  rf   r  r4   )r[   r\   r}  r   r   r   r   r^   s           r`   r  zPoly.invert
  si    & !S!QCKK::<qA155(#XXa[F'8446{rc   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  rf   r  r$  r4   r   rm  s      r`   r  zPoly.revert+
  sC    6 155(#UU\\#a&)F'844uuV}rc   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  rf   r  r4   rr   r   rd  s          r`   r  zPoly.subresultantsM
  sT      xx{31155/*__Q'F'?;;CV$%%rc   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  rf   r  r4   rr   r   )	r[   r\   r  r   r   r   r   r^   r  s	            r`   r  zPoly.resultantf
  s    . xx{31155+&KKjKA	Q';77q)4C+<==6!$$rc   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  rf   r  r4   r   r  s     r`   r  zPoly.discriminant
  sD     155.)UU'')F'>::uuVAu&&rc   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      r`   r  zPoly.dispersionset
  s    P 	9Q""rc   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      r`   r  zPoly.dispersion
  s    P 	6!Qrc   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  rf   r  r4   )	r[   r\   r   r   r   r   r  cffcfgs	            r`   r  zPoly.cofactors6  s`    ( xx{31155+&++a.KAsC';771vs3xS))rc   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  rf   r  r4   rd  s          r`   r  zPoly.gcdS  K     xx{31155% UU1XF'5116{rc   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  rf   r  r4   rd  s          r`   r  zPoly.lcmj  r  rc   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)rf   r   r   r  r  r4   r   )r[   pr^   s      r`   r  z
Poly.trunc  sV     EEIIa 155'"UU[[^F'733uuV}rc   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)rf   r   r{  r   r  r  r4   r   r   r}  r[   r^   s       r`   r  z
Poly.monic  s_    " AEEII%%

A155'"UU[[]F'733uuV}rc   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  rf   r  r4   r   r   r  s     r`   r  zPoly.content  r  rc   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  rf   r  r4   r   r   r   )r[   contr^   s      r`   r  zPoly.primitive  sY     155+&55??,LD&';77uuyy!!$'v66rc   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  rf   r  r4   rd  s          r`   r  zPoly.compose  sK     xx{31155)$YYq\F'9556{rc   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  rf   r   r4   rr   r   r   r  s     r`   r   zPoly.decompose  sE     155+&UU__&F';77Cv&''rc   c                     t        | j                  d      r| j                  j                  |      }nt        | d      | j	                  |      S )a  
        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')

        shift)r  rf   r  r4   r   )r[   r  r^   s      r`   r  z
Poly.shift  s>     155'"UU[[^F'733uuV}rc   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  rf   r  r4   r   )r[   r  rp  Pr~  r   r^   s          r`   r  zPoly.transform   s|     wwqz1wwqz1wwqz1155+&UU__QUUAEE2F';77uuV}rc   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)
rf   r   r{  r   r  r  r4   rr   r   r   r  s       r`   r  z
Poly.sturm:  sg    " AEEII%%

A155'"UU[[]F'733Cv&''rc   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  rf   r	  r4   r   )r[   r^   r\   rN  s       r`   r	  zPoly.gff_listW  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  rf   r  r4   r   )r[   rq  s     r`   r  z	Poly.normn  s;    8 155&!

A'622uuQxrc   c                     t        | j                  d      r| j                  j                         \  }}}nt        | d      || j	                  |      | j	                  |      fS )af  
        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  rf   r  r4   r   )r[   r  r\   rq  s       r`   r  zPoly.sqf_norm  sR    0 155*%eenn&GAq!':66!%%(AEE!H$$rc   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  rf   r  r4   r   r  s     r`   r  zPoly.sqf_part  r  rc   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  rf   r  r4   r   r   r   )r[   allr   factorsr\   rN  s         r`   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  rf   r  r4   r   )r[   r  r  r\   rN  s        r`   r  zPoly.sqf_list_include  sY    4 155,-ee,,S1G'+=>>*12$!Qq1222s   A%c                 n   t        | j                  d      r	 | j                  j                         \  }}nt        | d      | j                  j                  j                  |      |D cg c]  \  }}| j                  |      |f c}}fS # t        $ r 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  rf   r  r5   r   r  r4   r   r   r   )r[   r   r  r\   rN  s        r`   r  zPoly.factor_list  s    " 155-('!"!2!2!4w (=99uuyy!!%(W*MTQAEE!Ha=*MMM  'uu1vh&'
 +Ns   B +B1B.-B.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  rf   r  r5   r4   r   )r[   r  r\   rN  s       r`   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      r`   _realzPoly.intervals.<locals>._reale  s&    1AA77rc   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        r`   _complexz Poly.intervals.<locals>._complexl  sW    !*AAA2;;q>)99A2;;q>)99; ;rc   c                 j    | \  \  }}}t        j                  |      t        j                  |      f|fS r   r$  )r%  r  r  rN  s       r`   r&  zPoly.intervals.<locals>._realu  s/    $	AQQ8!<<rc   c                     | \  \  \  }}\  }}}t        j                  |      t        t        j                  |      z  z   t        j                  |      t        t        j                  |      z  z   f|fS r   r(  )r)  r*  r+  r  r  rN  s         r`   r,  z Poly.intervals.<locals>._complex|  sg    &/# !Q!Q!Q!BKKN*::Q!BKKN*::<=>@ @rc   )	r*   r   r  r  rf   r  r4   rr   r   )r[   r  r  r  r   r!  r"  r^   r&  r,  	real_partcomplex_parts               r`   r  zPoly.intervals9  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Qrc   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  rf   r2  r4   r   )	r[   r  r  r  r3  r!  	check_sqfr   Ts	            r`   r2  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~--rc   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   NegativeInfinityas_real_imagr*   r   rr   r   Infinityr  rf   r9  r4   r   r;  r   )r[   r  r   inf_realsup_realreimcounts           r`   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Erc   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   rG  s      r`   rootz	Poly.root  s&    6 {{&&--a-JJrc   c                     t         j                  j                  j                  j	                  | |      }|r|S t        |d      S )aL  
        Return a list of real roots with multiplicities.

        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)]

        rF  Fmultiple)rH  rI  rJ  CRootOf
real_rootsrG   )r[   rO  rG  realss       r`   rQ  zPoly.real_roots  s>      ''//::1x:PL//rc   c                     t         j                  j                  j                  j	                  | |      }|r|S t        |d      S )a  
        Return a list of real and complex roots with multiplicities.

        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)]

        rF  FrN  )rH  rI  rJ  rP  	all_rootsrG   )r[   rO  rG  rootss       r`   rT  zPoly.all_roots  s>    $ ''//99!h9OL//rc   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realr_  rq  rW  s    r`   <lambda>zPoly.nroots.<locals>.<lambda>u  s1    !&&QaQVVVZ[\[a[aVb,c rc   key   c                     | j                   rdnd| j                  t        | j                          | j                         fS r^  r_  rb  s    r`   rc  zPoly.nroots.<locals>.<lambda>|  s4    aff!QVVSQRQWQW[Z^_`_e_eZf0g rc   z$convergence to root failed; try n < z or maxsteps > )is_multivariater:   r  rf   r   r+   r-  r$  r*   rp  r   r   r=  mpmathmpcr  r5   mpdps$sympy.functions.elementary.complexesrW  	polyrootsrr   r   r"   sortedrM   )r[   r&  rY  rZ  r   r   denomsfacrl  rU  rW  s             @r`   nrootszPoly.nroots6  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|   )rh  r:   r  	is_linearr-  )r[   rU  factorrN  r  r  s         r`   ground_rootszPoly.ground_roots  sx     -3a79 9 + 	 IFA((*1qbd	 
 rc   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  )rh  r:   r"   
is_Integerr$  r  r   r    r  r   rT   r   )r[   r&  r  r   r  rq  s         r`   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rc   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    r`   rc  z Poly.same_root.<locals>.<lambda>  s    ~&?Q&GH rc   )rh  r:   rf   mignotte_sep_bound_squaredr   	get_fieldr   r   r   ra  r`  )r[   r  r  dom_delta_sqdelta_sqeps_sqrq  r   r&  evABr%  s               @r`   	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Crc   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   r3  r   )r[   r\   r  r   r   r   r   r^   cpcqr  rp  s               r`   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&)**rc   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   r   r+   r*   r  is_monicr   r  r  r  rS   r   r  )r[   fmr   r   s       r`   )make_monic_over_integers_by_scaling_rootsz.Poly.make_monic_over_integers_by_scaling_roots!  s    < !((2r(":KLL::!((b.bff9B??$DAq<<RVVa088:A==rc   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_irreducibler   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                     r`   galois_groupzPoly.galois_groupH  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rc   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

        )rf   is_zeror   s    r`   r  zPoly.is_zero~  s    " uu}}rc   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

        )rf   is_oner   s    r`   r  zPoly.is_one      " uu||rc   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

        )rf   r4  r   s    r`   r4  zPoly.is_sqf  r  rc   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

        )rf   r  r   s    r`   r  zPoly.is_monic  s    " uu~~rc   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

        )rf   is_primitiver   s    r`   r  zPoly.is_primitive      " uu!!!rc   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

        )rf   	is_groundr   s    r`   r  zPoly.is_ground  s    & uurc   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

        )rf   rt  r   s    r`   rt  zPoly.is_linear  s    " uurc   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

        )rf   is_quadraticr   s    r`   r  zPoly.is_quadratic  r  rc   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

        )rf   is_monomialr   s    r`   r  zPoly.is_monomial  s    " uu   rc   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

        )rf   is_homogeneousr   s    r`   r  zPoly.is_homogeneous+  s    , uu###rc   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

        )rf   r  r   s    r`   r  zPoly.is_irreducibleC  s    " uu###rc   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~   rU   r   s    r`   r   zPoly.is_univariateV      * 166{arc   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    r`   rh  zPoly.is_multivariatem  r  rc   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

        )rf   is_cyclotomicr   s    r`   r  zPoly.is_cyclotomic  s    , uu"""rc   c                 "    | j                         S r   )r_  r   s    r`   __abs__zPoly.__abs__      uuwrc   c                 "    | j                         S r   )ra  r   s    r`   __neg__zPoly.__neg__  r  rc   c                 $    | j                  |      S r   r  r[   r\   s     r`   __add__zPoly.__add__      uuQxrc   c                 $    |j                  |       S r   r  r  s     r`   __radd__zPoly.__radd__  r  rc   c                 $    | j                  |      S r   rg  r  s     r`   __sub__zPoly.__sub__  r  rc   c                 $    |j                  |       S r   r  r  s     r`   __rsub__zPoly.__rsub__  r  rc   c                 $    | j                  |      S r   r   r  s     r`   __mul__zPoly.__mul__  r  rc   c                 $    |j                  |       S r   r   r  s     r`   __rmul__zPoly.__rmul__  r  rc   r&  c                 R    |j                   r|dk\  r| j                  |      S t        S )Nr   )rx  rl  rW   )r[   r&  s     r`   __pow__zPoly.__pow__  s"    <<AF558O!!rc   c                 $    | j                  |      S r   rz  r  s     r`   
__divmod__zPoly.__divmod__  r  rc   c                 $    |j                  |       S r   r  r  s     r`   __rdivmod__zPoly.__rdivmod__  r  rc   c                 $    | j                  |      S r   r  r  s     r`   __mod__zPoly.__mod__  r  rc   c                 $    |j                  |       S r   r  r  s     r`   __rmod__zPoly.__rmod__  r  rc   c                 $    | j                  |      S r   r  r  s     r`   __floordiv__zPoly.__floordiv__  r  rc   c                 $    |j                  |       S r   r  r  s     r`   __rfloordiv__zPoly.__rfloordiv__  r  rc   r\   c                 D    | j                         |j                         z  S r   rY   r  s     r`   __truediv__zPoly.__truediv__      yy{199;&&rc   c                 D    |j                         | j                         z  S r   r  r  s     r`   __rtruediv__zPoly.__rtruediv__  r  rc   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)	rs   r   rU   r   r9   r5   r6   rf   r   )r   r  r[   r\   s       r`   __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     r`   __ne__zPoly.__ne__  s    6zrc   c                     | j                    S r   )r  r   s    r`   __bool__zPoly.__bool__  s    99}rc   c                 D    |s| |k(  S | j                  t        |            S r   )
_strict_eqr"   r[   r\   stricts      r`   eqzPoly.eq  s!    6M<<
++rc   c                 *    | j                  ||       S )Nr  )r  r  s      r`   nezPoly.ne   s    44&4)))rc   c                     t        || j                        xrB | j                  |j                  k(  xr' | j                  j	                  |j                  d      S NTr  )rR   r   rU   rf   r  r  s     r`   r  zPoly._strict_eq  s@    !Q[[)_aff.>_15588AEEZ^8C__rc   NNr   )FF)FTr   )r|   FNT)FNNNFFNNFFr8  rf  2   T)F   F)rZ   
__module____qualname____doc__	__slots__is_commutativers   _op_priorityrz   classmethodr   propertyr   rx   r   r   r   r   rT   rp   rq   rt   ru   rm   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ri   r   r  r   r  r  r  r   r  r!  r#  r   r   r  r-  r/  r1  r4  r6  r  r;  rY   rA  rC  rE  rH  rM  rQ  rS  rW  rY  r[  r]  r_  ra  r  rg  r   rj  rl  ro  rs  ru  rw  rz  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  r2  rD  rL  rQ  rT  rr  rv  ry  r  r  r  r  r  r  r4  r  r  r  rt  r  r  r  r  r   rh  r  r  r  rb   r  r  r  r  r  r  r   rW   r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  __classcell__r   s   @r`   rS   rS   e   s	   3j  INGL0>   E E ( (' ( (
 ( (
 ( (
 ( (
 A A& A A*  , ( (
 A A" 5 5<  :    ! !, O O N N O O81f+:0
)"J**%&!MF2D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@(56:&;* <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636JRX#.J=~K:0.02N`6&P1Df#+J%>N4l  $  $  $  $ " "$  (  $ " "$ ! !$ $ $. $ $$    ,    , # #.             ^$" %"             ^$' %' ^$' %' ( )" ^$ %,*`rc   rS   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. )rf   r   s    r`   r   zPurePoly._hashable_content  s    {rc   c                      t         |          S r   r   r   s    r`   r   zPurePoly.__hash__  r   rc   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    r`   r   zPurePoly.free_symbols  s    & ***rc   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  )rs   r   rU   r   r9   r5   r6   r~   rf   r   r   r7   r   )r   r  r[   r\   r   s        r`   r  zPurePoly.__eq__'  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  )rR   r   rf   r  r  s     r`   r  zPurePoly._strict_eq?  s-    !Q[[)JaeehhquuTh.JJrc   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       r`   r   zPurePoly._unify.<locals>.perY  r   rc   )r"   rs   rf   r   r   r   r6   r7   r~   rU   rR   r1   r   r   r   )r[   r\   rU   r   r   r   r   rw   s          @r`   r   zPurePoly._unifyB  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)rZ   r  r  r  r   r   r  r   r   rW   r  r  r   r  r  s   @r`   r  r    sJ    3" + +( ( ).K rc   r  c                 F    t        j                  ||      }t        | |      S r   )rj   rk   _poly_from_expr)r   rU   rx   ry   s       r`   poly_from_exprr!  e  s#     

d
+C4%%rc   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"   rR   r   r<   rs   r   rt   rU   r   rI  expandrC   rr   r   r   r(   r   r   ro   rS   rp   )r   ry   origr@  rf   r   r   r   s           r`   r   r   l  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rc   c                 F    t        j                  ||      }t        | |      S )(Construct polynomials from expressions. )rj   rk   _parallel_poly_from_expr)exprsrU   rx   ry   s       r`   parallel_poly_from_exprr)    s#     

d
+C#E3//rc   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~   rR   rS   r   rt   r   rU   r   rI  rr   r   r"   r   rs   appendr#  r<   rY   rD   $sympy.functions.elementary.piecewiser,  r9   r   r   extendr(   r   r   ro   rp   bool)r(  ry   r[   r\   origs_exprs_polysfailedr   r   repsr,  rN  coeffs_listlengthsr/  r-  rf   r   r   r   rI  r@  s                          r`   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	#:rc   c                 .    t        |       } || vr|| |<   | S )z7Add a new ``(key, value)`` pair to arguments ``dict``. )ro   )rx   re  r>  s      r`   _update_argsr9    s     :D
$S	Krc   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_Numberrs   rY   r!  r   Zeror<  rU   r~   r   r  rI   nextr   r  rR   r$  r   )r[   r   
gen_is_Numr  isNumr   r^   s          r`   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Mrc   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"   rs   rY   r;  rU   rS   r  r   )r[   rU   r  rvs       r`   r  r  >  sl    P 	
AyyIIK{{ 2;	 99>166D!T]'')2;rc   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)

    rI  r  r|   N)	rj   allowed_flagsr!  r<   r=   r  r3  r   r   )r[   rU   rx   r   ry   rx  degreess          r`   r  r  s  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

    rI  r  r|   Nr(  )rj   rC  r!  r<   r=   r  rh   r[   rU   rx   r   ry   rx  s         r`   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

    rI  r  r|   Nr(  )rj   rC  r!  r<   r=   r  rh   rY   )r[   rU   rx   r   ry   rx  r   s          r`   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

    rI  r  r|   Nr(  )rj   rC  r!  r<   r=   r  rh   rY   )r[   rU   rx   r   ry   rx  r   r   s           r`   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)

    rI  ro  r|  N)rj   rC  r)  r<   r=   ro  rI  rY   
r[   r\   rU   rx   r   r   ry   rx  rp  rq  s
             r`   ro  ro    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

    rI  rs  r|  N)rj   rC  r)  r<   r=   rs  rI  rY   	r[   r\   rU   rx   r   r   ry   rx  rq  s	            r`   rs  rs    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

    rI  ru  r|  N)	rj   rC  r)  r<   r=   ru  r;   rI  rY   	r[   r\   rU   rx   r   r   ry   rx  rp  s	            r`   ru  ru    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

    rI  rw  r|  N)rj   rC  r)  r<   r=   rw  rI  rY   rO  s	            r`   rw  rw  :  s    ( $	*2-q!fDtDtDA 	
A99yy{  2!S112rM  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}  rI  rz  r|  Nr}  )	rj   rC  r)  r<   r=   rz  r}  rI  rY   rJ  s
             r`   rz  rz  ]  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}  rI  r  r|  NrR  )	rj   rC  r)  r<   r=   r  r}  rI  rY   rL  s	            r`   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}  rI  r  r|  NrR  )	rj   rC  r)  r<   r=   r  r}  rI  rY   rO  s	            r`   r  r    rT  rU  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}  rI  r  r|  NrR  )	rj   rC  r)  r<   r=   r  r}  rI  rY   rO  s	            r`   r  r    s    ( $ 121-q!fDtDtDA 	
!A99yy{  1C001rU  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}  rI  Nr  r|  rR  )rj   rC  r)  r<   r(   r(  r  r   rl   r=   r}  rI  rY   )r[   r\   rU   rx   r   r   ry   rx  r   r  r  r  r  s                r`   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}  rI  Nr  r|  rR  )rj   rC  r)  r<   r(   r(  r  r   rl   r=   r}  rI  rY   )r[   r\   rU   rx   r   r   ry   rx  r   r  r  r  r  r  s                 r`   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:`~.mod_inverse` function:

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

    See Also
    ========

    sympy.core.numbers.mod_inverse

    r}  rI  Nr  r|  rR  )rj   rC  r)  r<   r(   r(  r   r  rl   r=   r}  rI  rY   )r[   r\   rU   rx   r   r   ry   rx  r   r  r  r  s               r`   r  r  .  s    B $ 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]

    rI  r  r|  N)rj   rC  r)  r<   r=   r  rI  rY   )
r[   r\   rU   rx   r   r   ry   rx  r^   rq  s
             r`   r  r  c  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

    rI  r  r|  Nr  )rj   rC  r)  r<   r=   r  rI  rY   )r[   r\   r  rU   rx   r   r   ry   rx  r^   r  rq  s               r`   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

    rI  r  r|   N)rj   rC  r!  r<   r=   r  rI  rY   r[   rU   rx   r   ry   rx  r^   s          r`   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)

    rI  Nr  r|  )rj   rC  r)  r<   r(   r(  r  r   rl   r=   rI  rY   )r[   r\   rU   rx   r   r   ry   rx  r   r  r  r  r  r  s                 r`   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   rK  r  r  r   seqr   numbersr^   numberrx   rU   s        r`   try_non_polynomial_gcdz(gcd_list.<locals>.try_non_polynomial_gcd  s    D.s3OFG{{"$$")!*gabk% F#ZZ7F}}V,	 v..rc   NrI  r|   c              3   P   K   | ]  }|j                   xr |j                     y wr   is_algebraicis_irrational.0r  s     r`   	<genexpr>zgcd_list.<locals>.<genexpr>  $     V3 0 0 FS5F5F FV   $&r  c              3   4   K   | ]  }|j                     y wr   is_rationalrn  frcs     r`   ro  zgcd_list.<locals>.<genexpr>       2s3??2   r   gcd_listr   )r"   rj   rC  r)  r~   r  ratsimpr  as_numer_denomr_  r<   r(  r=   rI  r   r<  rS   r  r  rY   )re  rU   rx   rh  r^   rI  ry   r  r  lstlcrv  rx  r@  s    ``           r`   ry  ry    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 argumentsrI  r   r  r|  )r  ry  r  rj   rC  r)  r   r"   rk  rl  rz  rt  r_  r{  r<   r(   r(  r   r  rl   r=   rI  rY   r[   r\   rU   rx   r   r   ry   r  r  rv  rx  r   r^   s                r`   r  r  B  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 rc  )r(   r   r   rK  r  rd  s        r`   try_non_polynomial_lcmz(lcm_list.<locals>.try_non_polynomial_lcm  s{    D.s3OFGvzz22$$")!*gabk% 8F#ZZ7F8 v..rc   NrI  r|   c              3   P   K   | ]  }|j                   xr |j                     y wr   rj  rm  s     r`   ro  zlcm_list.<locals>.<genexpr>  rp  rq  r  c              3   4   K   | ]  }|j                     y wr   rs  ru  s     r`   ro  zlcm_list.<locals>.<genexpr>  rw  rx  lcm_listr   r   )r"   r   r	   rj   rC  r)  r~   r  rz  r  r{  r<   r(  r=   rI  r   r  rS   rY   )re  rU   rx   r  r^   rI  ry   r  r  r|  r}  rv  rx  r@  s    ``           r`   r  r  v  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 argumentsrI  r|   r  r|  )r  r  r  rj   rC  r)  r   r"   rk  rl  rz  rt  r{  r<   r(   r(  r   r  rl   r=   rI  rY   r  s                r`   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   )rQ  )rn  r  rx   rU   s     r`   ro  zterms_gcd.<locals>.<genexpr>=  s      N!)A555Ns   z3Inequalities cannot be used with terms_gcd. Found: deepFr#  clearTrI  Nr  r|   )r  )!r"   rR   r   lhsrhsr   r  r	   is_Atomr  r_   rx   rQ  poprj   rC  r!  r<   r   r   r{  r|  r  r  r   r  r   r   rU   r   r   rY   as_coeff_Mul)r[   rU   rx   r$  r  r   r  r   ry   rx  r   denomr   r   r   terms    ``             r`   rQ  rQ    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}  rI  r  r|   N)	rj   rC  r!  r<   r=   r  r"   rI  rY   )r[   r  rU   rx   r   ry   rx  r^   s           r`   r  r  m  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}  rI  r  r|   NrR  )	rj   rC  r!  r<   r=   r  r}  rI  rY   r^  s          r`   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

    rI  r  r|   N)rj   rC  r!  r<   r=   r  rF  s         r`   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)

    rI  r  r|   N)rj   rC  r!  r<   r=   r  rI  rY   )r[   rU   rx   r   ry   rx  r  r^   s           r`   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

    rI  r  r|  N)rj   rC  r)  r<   r=   r  rI  rY   )	r[   r\   rU   rx   r   r   ry   rx  r^   s	            r`   r  r    s     $	*3-q!fDtDtDA YYq\F99~~  3	1c223rM  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]

    rI  r   r|   N)rj   rC  r!  r<   r=   r   rI  rY   r[   rU   rx   r   ry   rx  r^   rq  s           r`   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}  rI  r  r|   NrR  )	rj   rC  r!  r<   r=   r  r}  rI  rY   r  s           r`   r  r  ,  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

    rI  r	  r|   N)rj   rC  r!  r<   r=   r	  rI  rY   )	r[   rU   rx   r   ry   rx  r  r\   rN  s	            r`   r	  r	  J  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[   rU   rx   s      r`   gffr  y  s     :
;;rc   c                 B   t        j                  |dg       	 t        | g|i |\  }}|j                         \  }}}|j                  s*t        |      |j                         |j                         fS t        |      ||fS # t        $ r}t	        dd|      d}~ww xY 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)

    rI  r  r|   N)	rj   rC  r!  r<   r=   r  rI  r   rY   )	r[   rU   rx   r   ry   rx  r  r\   rq  s	            r`   r  r    s    & $	*41D1D13 jjlGAq!99qz199;		33qz1a  4
As334s   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

    rI  r  r|   N)rj   rC  r!  r<   r=   r  rI  rY   r^  s          r`   r  r    sz     $	*41D1D13 ZZ\F99~~  4
As334r_  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   rf   r~   rU   rn   r   r   r@  exprf   s       r`   re  z_sorted_factors.<locals>.key  s>    ID#((,,CS3tyy>3t{{3CSIIrc   c                     | \  }}|j                   j                   }t        |      t        |j                        |t        |j                        |fS r   r  r  s       r`   re  z_sorted_factors.<locals>.key  s>    ID#((,,CHc$))nc3t{{3CSIIrc   rd  )ro  )r  methodre  s      r`   _sorted_factorsr    s$    	J
	J
 's##rc   c                 f    t        | D cg c]  \  }}|j                         |z   c}} S c c}}w )z*Multiply a list of ``(expr, exp)`` pairs. )r   rY   )r  r[   rN  s      r`   _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  )rn  r[   r   rN  s      r`   ro  z(_symbolic_factor_list.<locals>.<genexpr>  s      Atq!!q& As   )r   r  r   	make_argsr  r  r;  rR   r	   r   is_PowbaseExp1rx   r-  r   rX   rx  is_positiver/  
is_integerrY   r  r<   r   r   r   )r   ry   r  r   r  r   rx   argr  r  r@  r   r_   _coeff_factorsr[   rN  r  rx  s                   `  r`   _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  rx   r  )rR   r	   r  r  r  rE   r   r  r_   rx   _symbolic_factorr   )r   ry   r  r   r  r  s         r`   r  r    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`. fracrI  r|   za polynomial expected, got %sr#  T)rj   rC  rk   r"   rR   r	   rS   rE   r{  r  r  r9   cloner   rs   r   r  rI  rY   )r   rU   rx   r  ry   numerr  r  fpr  fq_optr  r   r[   rN  r   r   s                     r`   _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  rj   rC  rk   r  r"   )r   rU   rx   r  r  ry   s         r`   _generic_factorr  I  sP    xx
D)H$#


d
+CC
OGDM377rc   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~   rU   r  r  r  r  r-  r   rt  r-  r
   rS   )r[   f1r&  r}  r   coeffx
rescale1_xcoeffs1r   	rescale_xr   r+  r  s               r`   _try_rescalez(to_rational_coeffs.<locals>._try_rescalez  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  rs  )zs    r`   rc  z<to_rational_coeffs.<locals>._try_translate.<locals>.<lambda>  s    !--4/ rc   Tbinary)r~   rU   r  r  r  r-  is_Addrt  rL   rx   r_   r  )
r[   r  r&  r   r   ratnonratalphaf2r  s
            r`   _try_translatez*to_rational_coeffs.<locals>._try_translate  s     166{aq	':':7NHHJ288:$VAY88AMMqvv/>KCQVVV_$Q&E%B"9rc   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_Rationalrp  minr  )	r  r   has_sqr   r   r[   r  wxrq  s	            r`   _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  rq  r  s         @r`   to_rational_coeffsr  R  s    L 1 D,& 	||~ 1! 4WWYBQ41tQqT))q"%AT1Q41--rc   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  rS   r  r  r  rY   r-  r   )r  r   r  p1r&  resr}  rq  r  r\   r  r   r1r  r  s                  r`   _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q6Mrc   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      r`   r  r    s      4e<<rc   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      r`   r"  r"    s     1dD77rc   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)])

    ru  r  r  r  s      r`   r  r  !  s      4h??rc   )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 d}	~	S t        |	      d}	~	w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.
            )ru  is_Mulr  )r   rq  rx   rU   s     r`   _try_factorzfactor.<locals>._try_factory  s0     ---CzzSZZ
Krc   ru  r  N)r"   r%   atomsr   r
   ru  r  r  xreplacer  r9   r  r   )
r[   r  rU   rx   r  partialsmuladdr  rq  msgs
     ``      r`   ru  ru  3  s    H 	
A	 a% c" 	"A*T*T*C

cjjcQh!	" zz(##'q$X>> 'Q<!#&&	's$   
B 	C"C	8C>C		C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  rS   r8   r  r)  r~   rU   r:   r   rf   r   r   r  rF   r   r-  )r   r  r  r  r   r  r!  r"  rI  ry   r   r@  r  r^   r  r  r  s                    r`   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) )E76E7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  r3  r!  r5  )rS   rR   r   	is_Symbolr9   r8   r2  )r[   r  r  r  r3  r!  r5  r   s           r`   r2  r2    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 polynomialr:  )rS   rR   r   r  r9   r8   rD  )r[   r  r   r   s       r`   rD  rD    so    (P5!!T"155?? "">?? ==Sc=**  PJQNOOPs   >A A+Tc                     	 t        | d      }t        | t               s!|j                  j                  st	        d      |j                  |      S # t
        $ r t	        d| z        w xY w)z
    Return a list of real roots with multiplicities of ``f``.

    Examples
    ========

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

    >>> real_roots(2*x**3 - 7*x**2 + 4*x + 4)
    [-1/2, 2, 2]
    Fr  r  z1Cannot compute real roots of %s, not a polynomialrN  )rS   rR   r   r  r9   r8   rQ  )r[   rO  r   s      r`   rQ  rQ    ss    	E5!!T"155?? "">??
 <<<**	  E?!CE 	EE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)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&  rY  rZ  )rS   rR   r   r  r9   r8   rr  )r[   r&  rY  rZ  r   s        r`   rr  rr  (  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  rv  r|   N)rj   rC  r!  rR   rS   r   r  r9   r<   r=   rv  rF  s         r`   rv  rv  G  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  ry  r|   N)rj   rC  r!  rR   rS   r   r  r9   r<   r=   ry  rI  rY   )r[   r&  rU   rx   r   ry   rx  r^   s           r`   ry  ry  e  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)sringrI  T)radicalr|  rU   r   zunexpected argument: %sr+  c                 H    | j                   du xr | j                         S r  )r  has)r   r,  s    r`   rc  zcancel.<locals>.<lambda>  s'      D(Ay1A-A rc   r  Nr|   F).r  r  sympy.polys.ringsr  rj   rC  r"   rR   r3  r   r;  r   r	   r   r{  r~   rS   rU   r   r  rY   r  r.  r,  r
  r9   ngensr#  r   r  r  r  r  rL   rx   r  r_   r$   r=  r&   r-  skiprl   r  ro   r   )r[   r  rU   rx   r  r  ry   r  rp  r  r   r   r  r   ncr   r5  poter  r~  r,  s                        @r`   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)

    rI  r}  reducedr   NFr   Txringr|   )rj   rC  r)  rr   r<   r=   r   r}  r{  r|  r  r  r  r  rU   rh   r   r   rf   r   r   rz  rS   rp   ro   r  r6   rI  rY   )r[   r   rU   rx   rI  ry   rx  r   r!  r  _ringr   r   r@  r~  rq  rp  _Q_rs                      r`   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   rU   rx   s      r`   r.   r.   4  s    f *T*T**rc   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      r`   r  r  j  s     *T*T*>>>rc   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. rI  r  r.   Nr   )PolyRingr  )rj   rC  r)  r<   r=   r~   r  r  rU   r   rh   r   rf   r   	_groebnerr  rS   rp   _new)rw   r   rU   rx   rI  ry   rx  r  ringr@  r   r\   s               r`   rz   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   rz   r3  _basis_options)rw   basisrj   r   s       r`   r!  zGroebnerBasis._new  s'    mmC 5\

rc   c                 p    d | j                   D        }t        | t        | j                  j                   fS )Nc              3   <   K   | ]  }|j                           y wr   r  )rn  r  s     r`   ro  z%GroebnerBasis.args.<locals>.<genexpr>  s     22s   )r$  r   r%  rU   )r   r&  s     r`   rx   zGroebnerBasis.args  s.    2dkk2uudmm&8&89::rc   c                 \    | j                   D cg c]  }|j                          c}S c c}w r   )r$  rY   r   r@  s     r`   r(  zGroebnerBasis.exprs  s     +/;;74777s   )c                 ,    t        | j                        S r   )rr   r$  r   s    r`   rI  zGroebnerBasis.polys  s    DKK  rc   c                 .    | j                   j                  S r   )r%  rU   r   s    r`   rU   zGroebnerBasis.gens  s    }}!!!rc   c                 .    | j                   j                  S r   )r%  r   r   s    r`   r   zGroebnerBasis.domain  s    }}###rc   c                 .    | j                   j                  S r   )r%  rh   r   s    r`   rh   zGroebnerBasis.order  s    }}"""rc   c                 ,    t        | j                        S r   )r~   r$  r   s    r`   __len__zGroebnerBasis.__len__  s    4;;rc   c                     | j                   j                  rt        | j                        S t        | j                        S r   )r%  rI  iterr(  r   s    r`   r  zGroebnerBasis.__iter__  s-    ==

##

##rc   c                 r    | j                   j                  r| j                  }||   S | j                  }||   S r   )r%  rI  r(  )r   itemr&  s      r`   __getitem__zGroebnerBasis.__getitem__  s9    ==JJE T{ JJET{rc   c                 r    t        | j                  t        | j                  j	                               f      S r   )hashr$  r3  r%  r   r   s    r`   r   zGroebnerBasis.__hash__  s(    T[[%(;(;(=">?@@rc   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)rR   r   r$  r%  rK   rI  rr   r(  r   r  s     r`   r  zGroebnerBasis.__eq__  sd    eT^^,;;%,,.R4==ENN3RRe_::e,I

d5k0IIrc   c                     | |k(   S r   r  r9  s     r`   r  zGroebnerBasis.__ne__  s    5=  rc   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   r0  )monomials    r`   
single_varz5GroebnerBasis.is_zero_dimensional.<locals>.single_var  s    s4*+q00rc   r   r(  )r/   r~   rU   r%  rh   rI  r  r  )r   r?  r  rh   r@  r>  s         r`   r  z!GroebnerBasis.is_zero_dimensional  sr    	1 aSTYY/0	##JJ 	&DwwUw+H(#X%			& 9~rc   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)r   rh   r   r  Tr  r|   )r%  rh   r0   r  rl   rr   r$  r   r  r  r  r  rU   r   r   rf   r   r   r-   rS   rp   ro   r|  r  r!  )r   rh   ry   	src_order	dst_orderrI  r   r  r  r   r   r@  r   r\   s                 r`   fglmzGroebnerBasis.fglm  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

        Fr   Tr   r  r|   N)rS   ru   r%  rr   r$  r   r{  r|  r  r  r  r  rU   rh   r   r   rf   r   r   rz  rp   ro   r  r6   rI  rY   )r   r   r}  r@  rI  ry   r   r!  r  r  r   r   r~  rq  rp  r  r  s                    r`   r   zGroebnerBasis.reduce6  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   r*  s     r`   containszGroebnerBasis.containsw  s    & {{4 #q((rc   Nr  )rZ   r  r  r  rz   r  r!  r  rx   r(  rI  rU   r   rh   r0  r  r5  r   r  r  r  rC  r   rF  r  rc   r`   r  r  |  s    / &   ; ; 8 8 ! ! " " $ $ # # $A!  >@!D?B)rc   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                 f   g g }}t        j                  |       D ]l  }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                  |      } |rKt        | }|j                  r|j                  |      }n%|j                  t        j                  ||            }|j	                  |       o |st        j                  | |      }	nm|d   }	|dd  D ]  }|	j                  |      }	 |rKt        | }|j                  r|	j                  |      }	n%|	j                  t        j                  ||            }	 |	j                  |j!                  dd      i S )Nr   r|   rU   r  )r
   r  r   r  r-  r  r  r  rx  rl  r   r;  rS   ru   r  r   r  )r   ry   r  
poly_termsr  r  poly_factorsru  productr^   _polyrx   s             r`   rL  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''")++f"5")++doofc.J"K!!'*;	+> __T3/F]F"12 *D)* E{>>#ZZ-F#ZZc(BCFv~~swwvr2;d;;rc   r#  F)rj   rC  r"   rs   rS   rk   )r   rU   rx   ry   rL  s     ` @r`   r@  r@    sr     $#2<h 4=D||D(4(4((tX


d
+Csrc   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    rS   rY   )	r&  r[   Kr  r   rI  headtailr@  s	            r`   
named_polyrQ    s    0 	1uT1EFF1qu$Dy"4t44qQ"$""A&D|||D%*-xxd#4,dlln,rc   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.numbersr   r   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'   rj   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   rH  ri  mpmath.libmp.libhyperrM   rb   rS   r  r!  r   r)  r'  r9  r  r  r  r  r  r  ro  rs  ru  rw  rz  r  r  r  r  r  r  r  r  r  r  ry  r  r  r  rQ  r  r  r  r  r  r   r  r	  r  r  r  r  r  r  r  r  r  r  r  r  r"  r  ru  r  r2  rD  rQ  rr  rv  ry  r  r  r  r  r@  rQ  r  rc   r`   <module>rt     s   > $    # , A AM M * + = = 6 & + 0 > + . 4 * * ; - ; * . 1 1	 	 	 	  / A 5 5 @ 4   /D ^B`5 ^B` ^B`BE 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 1 1h  : &+ ! !H  : % %P Q Qh 0 0f J JZ / /d r3 r3j  :  :  0 * *Z  :  :  : + +\ < <
    B  :$ 6
7t)FX8|~)X = =" 8 8" @ @"  _' _'D 4 4n U U8 + +@ + +6 = =<  : ( (V # cC cCL 8 8v 2+ 2+j ? ?" M)E M) M)` N Nb"-rc   