You can describe polynomial without classes. Any polynomial is defined by its coefficients, so standard data types such as tuple or list can describe a polynomial.
We wish to print the polynomial in human readable form:
a function, e.g.
my_polynomial = (1, 2, 3) # we assume that we have a polynomial: 1*x^0 + 2*x + 3*x^2Further, we need some helper functions that will allow to perform basic operations over such polynomials.
We wish to print the polynomial in human readable form:
def print_polynomial(p, default_argument_name='x'): """Print polynomial p: a list or a tuple, polynomial coefficients """ result = '' for power, coefficient in enumerate(p): result += '{}*{}^{} +'.format(coefficient, default_argument_name, power) # This is dirty implementation, it doesn't handle +/- signs properly print(result[:-1]) # drop `+`Also, we would like to calculate value of the polynomial at specified point. So, we need to define
a function, e.g.
get_polynomial_value
, def get_polynomial_value(p, x): """Evaluates polynomial at specified point """ result = 0.0 for power, coefficient in enumerate(p): result += coefficient * x ** power return resultYou can also wish to be able to export polynomial to Tex/LaTex-format. Thats easy, just write a helper function for this.
def export_to_latex(p): """Returns latex-formatted representation of a polynomial""" result = r"" for power, coefficient in enumerate(p): result += r'{coefficient}\cdot x^{}'.format(coefficient, power) + '+' if (power != len(coefficient)) else '' # drop `+` for the last polynomial term return resultI didn't test these function. You can definitely improve them (e.g. an issue with +/- handling when printing a polynomial), define you own help functions, e.g. define
add_polynomials(p1, p2)
, multiply_polynomials(p1,p1)
etc.