Now it's simple - you really only want a function in Python that does the numeric calculation of the polynomial, defined by the coefficients in P.
Then you only have to do a for
by traversing the coefficients, and using enmerate
to have the exponent of X associated with each coefficient. The enumerate
works like this: for each element of a sequence, it returns another two-element sequence in which the first is the index and the second is the element itself.
Then we calculate each portion of the polynomial and add them all up - doing "in extenso":
def F(P, x):
result = 0
for exponent, coeficient in enumerate(P):
result += coeficient * x ** exponent
return result
It works if P is a list or any other sequence, since for
in Python always traverses a sequence.
There is a more advanced syntax that also allows the use of for as an "inline" expression, not as a command on a separate line. This template creates a "generator expression" that can be passed directly to the built-in function sum
:
def F(P, x):
return sum(c * x ** e for (e, c) in enumerate(P))
And last but not least, you can have a polynomial class - and over time add features to it - if the class receives a list of coefficients in its __init__
, it can have a __call__
which allows its polynomial to calculate its value for a given "x" - and a __repr__
that has a legal representation of the polynomial:
class Poli:
def __init__(self, coeficients):
self.coeficients = coeficients
@property
def degree(self):
return len(coeficients) - 1
def __call__(self, x):
return sum(c * x ** e for (e, c) in enumerate(self.coeficients))
def __repr__(self):
return f"P({})".format(" + ".join(f"{c} * x ** {e}" for e, c in enumerate(self.coeficients))