class Polynomial:
|
def __init__(self, *argv: float):
|
if len(argv) < 1:
|
raise ValueError("A Polynomial has at least one coefficient.")
|
if argv[-1] == 0:
|
raise ValueError("The coefficient at the highest degree must not be zero.")
|
self.__coefficients = tuple(argv)
|
self.__order = len(argv)
|
|
def evaluate(self, x: float) -> tuple[float, list[float]]:
|
p = self.__coefficients[-1]
|
c = [p]
|
for ak in self.__coefficients[-2::-1]:
|
p = ak + (p * x)
|
c.insert(0, p)
|
return c[0], c[1:]
|
|
def order(self):
|
return self.__order
|
|
def __add__(self, other: "Polynomial") -> "Polynomial":
|
if not isinstance(other, Polynomial):
|
raise ValueError("Operator + is only applicable for Polynomial.")
|
coefficients = []
|
if self.__order > other.__order:
|
low_order = other.__order
|
heigh_order = self.__order
|
higher_coefficients = self.__coefficients
|
else:
|
low_order = self.__order
|
heigh_order = other.__order
|
higher_coefficients = other.__coefficients
|
|
for i in range(0, low_order):
|
coefficients.append(self.__coefficients[i] + other.__coefficients[i])
|
for j in range(i+1, heigh_order):
|
coefficients.append(higher_coefficients[j])
|
return Polynomial(*coefficients)
|
|
def __getitem__(self, key):
|
return self.__coefficients[key]
|
|
|
def __repr__(self) -> str:
|
coe = []
|
for c in self.__coefficients:
|
coe.append(f'{c}')
|
return ' '.join(coe)
|