Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Complex():
- def __init__(self, real, imag):
- self.a = real
- self.b = imag
- def __repr__(self):
- return "Complex(" + str(self.a) + ", " + str(self.b) + ")"
- def __str__(self):
- if self.a == 0 and self.b == 0:
- return '0'
- elif self.a == 0:
- return str(self.b) + "i"
- elif self.b == 0:
- return str(self.a)
- elif self.b < 0:
- return str(self.a) + " - " + str(-self.b) + "i"
- else:
- return str(self.a) + " + " + str(self.b) + "i"
- def conjugate(self):
- return Complex(self.a, -self.b)
- def __add__(self):
- if type(other) is int or type(other) is float:
- other = Complex(other, 0)
- return Complex(self.a + other.a, self.b + other.b)
- def __radd__(self):
- return self.__add__(other)
- def __sub__(self):
- return self + (other * -1)
- def __rsub__(self, other):
- return (self * -1) + other
- def __mul__(self):
- if type(other) is int or type(other) is float:
- other = Complex(other, 0)
- real = (self.a * other.a) - (self.b * other.b)
- imag = (self.a * other.b) + (self.b * other.a)
- return Complex(real, imag)
- def __rmul__(self):
- return self * other
- c1 = Complex(2, 4)
- c2 = 5
- c3 = c2 - c1
- print(c3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement