Advertisement
Guest User

Untitled

a guest
Oct 17th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. class Complex():
  2. def __init__(self, real, imag):
  3. self.a = real
  4. self.b = imag
  5.  
  6. def __repr__(self):
  7. return "Complex(" + str(self.a) + ", " + str(self.b) + ")"
  8.  
  9. def __str__(self):
  10. if self.a == 0 and self.b == 0:
  11. return '0'
  12. elif self.a == 0:
  13. return str(self.b) + "i"
  14. elif self.b == 0:
  15. return str(self.a)
  16. elif self.b < 0:
  17. return str(self.a) + " - " + str(-self.b) + "i"
  18. else:
  19. return str(self.a) + " + " + str(self.b) + "i"
  20.  
  21. def conjugate(self):
  22. return Complex(self.a, -self.b)
  23.  
  24. def __add__(self):
  25. if type(other) is int or type(other) is float:
  26. other = Complex(other, 0)
  27.  
  28. return Complex(self.a + other.a, self.b + other.b)
  29.  
  30. def __radd__(self):
  31. return self.__add__(other)
  32.  
  33. def __sub__(self):
  34.  
  35. return self + (other * -1)
  36.  
  37. def __rsub__(self, other):
  38. return (self * -1) + other
  39.  
  40. def __mul__(self):
  41. if type(other) is int or type(other) is float:
  42. other = Complex(other, 0)
  43.  
  44. real = (self.a * other.a) - (self.b * other.b)
  45. imag = (self.a * other.b) + (self.b * other.a)
  46.  
  47. return Complex(real, imag)
  48.  
  49. def __rmul__(self):
  50. return self * other
  51.  
  52.  
  53.  
  54.  
  55. c1 = Complex(2, 4)
  56. c2 = 5
  57. c3 = c2 - c1
  58.  
  59. print(c3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement