Advertisement
Guest User

Untitled

a guest
Dec 15th, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. class Polynomial:
  2.  
  3. terms = {}
  4. def __init__(self, termdict):
  5. self.terms = termdict
  6.  
  7. def __getitem__(self, exp):
  8. return self.terms[exp]
  9.  
  10. def __str__(self):
  11. output = ""
  12. count = 0
  13. for i in self.terms:
  14. if (count != 0):
  15. if (self.terms[i] < 0): output += " - "
  16. else: output += " + "
  17. if (i == 1): output += str(abs(self.terms[i])) + "x"
  18. elif (i == 0): output += str(abs(self.terms[i]))
  19. else: output += str(abs(self.terms[i])) + "x^" + str(i)
  20. count += 1
  21. return output
  22.  
  23. def __len__(self):
  24. return max(self.terms.keys())
  25.  
  26. def __add__(self, poly2):
  27. z = self.terms.copy()
  28. z.update(poly2.terms)
  29. for i in z:
  30. if (i in self.terms and i in poly2.terms):
  31. z[i] = self.terms[i] + poly2.terms[i]
  32. return Polynomial(z)
  33.  
  34. def __sub__(self, poly2):
  35. z = self.terms.copy()
  36. z.update(poly2.terms)
  37. for i in z:
  38. if (i in self.terms and i in poly2.terms):
  39. z[i] = self.terms[i] - poly2.terms[i]
  40. if (i in poly2.terms and i not in self.terms):
  41. z[i] = poly2.terms[i] * -1
  42. return Polynomial(z)
  43.  
  44.  
  45. #polynomial = {exponent:coefficient, exponent:cofficient...}
  46. p1 = {13:5, 2:10, 1:-5, 0:44}
  47. p2 = {9999:5, 2:20, 1:-5, 0:40}
  48.  
  49. poly1 = Polynomial(p1)
  50.  
  51. print(poly1.terms)
  52. print(poly1[2])
  53. print(poly1)
  54. print(len(poly1))
  55. print()
  56.  
  57. poly2 = Polynomial(p2)
  58. poly_added = poly1 + poly2
  59. poly_subtracted = poly1 - poly2
  60.  
  61. print(poly1)
  62. print(poly2)
  63. print(poly_added)
  64. print(poly_subtracted)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement