class ComplexNumber: def __init__(self, real, imag): self.real = real self.imag = imag def __str__(self): if self.real == 0: return f'{self.imag:g}j' if self.imag < 0: return f'({self.real:g}{self.imag:g}j)' return f'({self.real:g}+{self.imag:g}j)' def __abs__(self): return (self.real ** 2 + self.imag ** 2) ** 0.5 def __eq__(self, other): return self.real == other.real and self.imag == other.imag def __add__(self, other): return ComplexNumber(self.real + other.real, self.imag + self.imag) def __sub__(self, other): return ComplexNumber(self.real - other.real, self.imag - other.imag) def __mul__(self, other): return ComplexNumber(self.real * other.real - self.imag * other.imag, self.real * other.imag + self.imag * other.real) def __truediv__(self, other): sr, si, orr, oi = self.real, self.imag, other.real, other.imag r = float(orr**2 + oi**2) return ComplexNumber((sr*orr+si*oi) / r, (si*orr-sr*oi) / r) def conjugate(self): return ComplexNumber(self.real, -self.imag) def test_ComplexNumber(a, b): py_cnum, my_cnum = complex(a, b), ComplexNumber(a, b) # Validate the constructor. if my_cnum.real != a or my_cnum.imag != b: print("__init__() set self.real and self.imag incorrectly") # Validate conjugate() by checking the new number's imag attribute. if py_cnum.conjugate().imag != my_cnum.conjugate().imag: print("conjugate() failed for", py_cnum) # Validate __str__(). if str(py_cnum) != str(my_cnum): print("__str__() failed for", py_cnum) # Validate __abs__(). if str(abs(py_cnum)) != str(abs(my_cnum)): print("__abs__() failed for", py_cnum) # Validate __eq__(). if str(py_cnum) != str(my_cnum): print("__eq__() failed for", py_cnum) # Validate __add__(). if str(py_cnum + py_cnum) != str(my_cnum + my_cnum): print(print("__add__() failed for", py_cnum)) # Validate __sub__(). if str(py_cnum - py_cnum) != str(my_cnum - my_cnum): print(print("__sub__() failed for", py_cnum)) # Validate __mul__(). if str(py_cnum * py_cnum) != str(my_cnum * my_cnum): print(print("__mul__() failed for", py_cnum)) # Validate __truediv__(). if str(py_cnum / py_cnum) != str(my_cnum / my_cnum): print(py_cnum / py_cnum, my_cnum / my_cnum) print(print("__truediv__() failed for", py_cnum)) test_ComplexNumber(3, 4)