Answer to Question #205943 in Python for siva

Question #205943

how to write the program for polynomials


1
Expert's answer
2021-06-13T07:06:38-0400

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()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS