In mathematics, a polynomial or multinomial in one variable $$x$$ is an expression of the format: \[a_0+a_1 x+ a_2x^2+\dots+a_n x^n\] where $$n$$ is an integer and the numbers $$a_k$$ ($$k=0,\dots,n$$) are named the coefficients of the polynomial. Polynomials form an important class of functions with many applications. They are used for complex functions, among other things.

Assignment

To simplify matters, we will confine ourselves to polynomials that only have whole coefficients. The assignments consists of making a class Polynomial. The class contains the following methods:

  1. The initializing method __init__. The coefficients in the polynomial are given to the constructor as a list. Index $$i$$ in the list then represents the coefficient of the $$x^i$$ term in the polynomial. Any possible zero-coefficients at the end of the list must be left out and may not be saved in the attribute of the class.

  2. The method __str__. Make sure that your polynomial is written out in the format that is given in the examples below. That is: terms with a zero as coefficient are left out, coefficients that are one are left out, etc. If all coefficients are zero, 0 is printed as a polynomial.

  3. The method __repr__. This method prints a string-expression that would make an object with the same value as when it were to be evaluated.

  4. The method __neg__ that implements the negation of a polynomial.

    >>> p = Polynomial([1, -1])
    >>> print(-p) 
    - 1 + x

  5. The method __add__ that allows to sum up two polynomials.

  6. The method __sub__ that allows subtracting two polynomials.

  7. The method __mul__ that multiplies two polynomials. If \[p(x)=\sum_{i=0}^m c_ix^i\] and \[q(x)=\sum_{j=0}^n d_jx^j\] are two polynomials, their product is \[\left(\sum_{i=0}^m c_ix^i\right)\left(\sum_{j=0}^n d_jx^j\right)=\sum_{i=0}^m\sum_{j=0}^nc_id_jx^{i+j}.\]

  8. The method derivative that prints a new polynomial as a result, namely the derivative of the original polynomial. The derivative of a polynomial \[\sum_{i=0}^n c_ix^i\] is given by \[\sum_{i=1}^nic_ix^{i-1}.\]

Example

>>> p = Polynomial([1, -1])
>>> print(p)
1 - x
>>> p
Polynomial([1, -1])
>>> q = Polynomial([0, 1, 0, 0, -6, -1])
>>> print(q)
x - 6 * x^4 - x^5
>>> q
Polynomial([0, 1, 0, 0, -6, -1])
>>> print(p + q)
1 - 6 * x^4 - x^5
>>> print(-p)
- 1 + x
>>> print(p - q)
1 - 2 * x + 6 * x^4 + x^5
>>> print(p * q)
x - x^2 - 6 * x^4 + 5 * x^5 + x^6
>>> print(q.derivative())
1 - 24 * x^3 - 5 * x^4
>>> Polynomial([1, -1, 0, 0, 0]) 
Polynomial([1, -1])
>>> w = Polynomial([0, 1, 0, 0, 5, -1])
>>> print(q - w) 
- 11 * x^4