Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Polynomial:
- terms = {}
- def __init__(self, termdict):
- self.terms = termdict
- def __getitem__(self, exp):
- return self.terms[exp]
- def __str__(self):
- output = ""
- count = 0
- for i in self.terms:
- if (count != 0):
- if (self.terms[i] < 0): output += " - "
- else: output += " + "
- if (i == 1): output += str(abs(self.terms[i])) + "x"
- elif (i == 0): output += str(abs(self.terms[i]))
- else: output += str(abs(self.terms[i])) + "x^" + str(i)
- count += 1
- return output
- def __len__(self):
- return max(self.terms.keys())
- def __add__(self, poly2):
- z = self.terms.copy()
- z.update(poly2.terms)
- for i in z:
- if (i in self.terms and i in poly2.terms):
- z[i] = self.terms[i] + poly2.terms[i]
- return Polynomial(z)
- def __sub__(self, poly2):
- z = self.terms.copy()
- z.update(poly2.terms)
- for i in z:
- if (i in self.terms and i in poly2.terms):
- z[i] = self.terms[i] - poly2.terms[i]
- if (i in poly2.terms and i not in self.terms):
- z[i] = poly2.terms[i] * -1
- return Polynomial(z)
- #polynomial = {exponent:coefficient, exponent:cofficient...}
- p1 = {13:5, 2:10, 1:-5, 0:44}
- p2 = {9999:5, 2:20, 1:-5, 0:40}
- poly1 = Polynomial(p1)
- print(poly1.terms)
- print(poly1[2])
- print(poly1)
- print(len(poly1))
- print()
- poly2 = Polynomial(p2)
- poly_added = poly1 + poly2
- poly_subtracted = poly1 - poly2
- print(poly1)
- print(poly2)
- print(poly_added)
- print(poly_subtracted)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement