how to write the program for polynomials
For example like this:
class Polynomial:
def __init__(self, coeff):
self.coeff = coeff
def __add__(self, other):
i = len(self.coeff)
j = len(other.coeff)
k = max(i, j)
coeff = [0] * k
while i > 0 and j > 0:
i, j, k = i - 1, j - 1, k - 1
coeff[k] = self.coeff[i] + other.coeff[j]
while i > 0:
i, k = i - 1, k - 1
coeff[k] = self.coeff[i]
while j > 0:
j, k = j - 1, k - 1
coeff[k] = other.coeff[j]
return Polynomial(coeff)
def __sub__(self, other):
pass
def __mul__(self, other):
pass
def __str__(self):
poly = 'y(x)='
l = len(self.coeff)-1
for i in range(l, -1, -1):
c = self.coeff[l-i]
if c != 0:
poly += ('-' if c < 0 else '+') + str(abs(c)) + 'x^' + str(i)
return poly
def main():
p1 = Polynomial([3, 2, -4, 4.2, 5, 0, 5])
print(p1)
p2 = Polynomial([-3, 4, 3, 0, -1])
print(p2)
print(p1 + p2)
if __name__ == '__main__':
main()
Comments
Leave a comment