In [1]:
import sympy as sym
import numpy as np
import math

from IPython.display import display, Math
from sympy.abc import w,x,y,z,a,b,c,d
sym.init_printing()
In [2]:
p1 = 2*x**3+x**2-x
p2 = x**3-x**4-4*x**2

p1
Out[2]:
$$2 x^{3} + x^{2} - x$$
In [3]:
p2
Out[3]:
$$- x^{4} + x^{3} - 4 x^{2}$$
In [4]:
p1+p2
Out[4]:
$$- x^{4} + 3 x^{3} - 3 x^{2} - x$$
In [5]:
display(Math('(%s)+(%s)=%s' %(sym.latex(p1),sym.latex(p2),sym.latex(p1+p2))))
$\displaystyle (2 x^{3} + x^{2} - x)+(- x^{4} + x^{3} - 4 x^{2})=- x^{4} + 3 x^{3} - 3 x^{2} - x$
In [6]:
display(Math('(%s)-(%s)=%s' %(sym.latex(p1),sym.latex(p2),sym.latex(p1-p2))))
$\displaystyle (2 x^{3} + x^{2} - x)-(- x^{4} + x^{3} - 4 x^{2})=x^{4} + x^{3} + 5 x^{2} - x$
In [7]:
p1 = sym.Poly(2*x**3+x**2-x)
type(p1)
Out[7]:
sympy.polys.polytools.Poly
In [8]:
p1
Out[8]:
$$\operatorname{Poly}{\left( 2 x^{3} + x^{2} - x, x, domain=\mathbb{Z} \right)}$$
In [9]:
p1.eval(0)
Out[9]:
$$0$$
In [10]:
p1.coeffs()
Out[10]:
$$\left [ 2, \quad 1, \quad -1\right ]$$
In [11]:
polys = [sym.Poly(2*x+x**2), sym.Poly(-x**3+4*x), sym.Poly(x**5-x**4+x/4+4)]
polys
Out[11]:
$$\left [ \operatorname{Poly}{\left( x^{2} + 2 x, x, domain=\mathbb{Z} \right)}, \quad \operatorname{Poly}{\left( - x^{3} + 4 x, x, domain=\mathbb{Z} \right)}, \quad \operatorname{Poly}{\left( x^{5} - x^{4} + \frac{x}{4} + 4, x, domain=\mathbb{Q} \right)}\right ]$$
In [12]:
p1.degree()
Out[12]:
$$3$$
In [13]:
for poli in polys:
    if np.mod(poli.degree(),2)==0: #poli.degree()%2==0
        print('The degree of %s is even, and the coefficients sum to %g. ' %(poli.as_expr(), sum(poli.coeffs())))
    else:
        print('The degree of %s is odd, and there are %gcoefficients. ' %(poli.as_expr(), sum(poli.coeffs())))
    
The degree of x**2 + 2*x is even, and the coefficients sum to 3. 
The degree of -x**3 + 4*x is odd, and there are 3coefficients. 
The degree of x**5 - x**4 + x/4 + 4 is odd, and there are 4.25coefficients.