polynomial assignment

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.3 kB
1
Indexable
Never
class Polynomial:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def __repr__(self):
        return f"{self.a}x^2+{self.b}x+{self.c}"

    def __add__(self, other):
        # Adding the coefficients
        a_sum = self.a + other.a
        b_sum = self.b + other.b
        c_sum = self.c + other.c

        # Creating a new Polynomial object with sum of coefficients
        result = Polynomial(a_sum, b_sum, c_sum)
        return result

    def __sub__(self, other):
        # Subtracting the coefficients
        a_sub = self.a - other.a
        b_sub = self.b - other.b
        c_sub = self.c - other.c

        # Creating a new Polynomial object with subtract of coefficients
        result = Polynomial(a_sub, b_sub, c_sub)
        return result


obj1 = Polynomial(1, 3, 4)
obj2 = Polynomial(5, 3, 6)

# Add two Polynomial obj and store it in a new Polynomial object
sum_polynomial = obj1 + obj2

# Subtract two Polynomial obj and store it in a new Polynomial object
subtract_polynominal = obj1 - obj2

print('First polynomial is:',obj1)
print('Second polynomial is:',obj2)

print("Sum of polynomials is:", sum_polynomial)
print("Subtract of polynomials is:", subtract_polynominal)