|
| 1 | +# Classes: Dealing with Complex Numbers |
| 2 | +# https://www.hackerrank.com/challenges/class-1-dealing-with-complex-numbers/problem |
| 3 | + |
| 4 | +from math import sqrt |
| 5 | + |
| 6 | +class ComplexNumber(object): |
| 7 | + def __init__(self, x=0, y=0): |
| 8 | + self.real_p = x |
| 9 | + self.imag_p = y |
| 10 | + |
| 11 | + def __add__(self, other): |
| 12 | + s = ComplexNumber() |
| 13 | + s.real_p = self.real_p + other.real_p |
| 14 | + s.imag_p = self.imag_p + other.imag_p |
| 15 | + return s |
| 16 | + |
| 17 | + def __sub__(self, other): |
| 18 | + s = ComplexNumber() |
| 19 | + s.real_p = self.real_p - other.real_p |
| 20 | + s.imag_p = self.imag_p - other.imag_p |
| 21 | + return s |
| 22 | + |
| 23 | + def __mul__(self, other): |
| 24 | + s = ComplexNumber() |
| 25 | + s.real_p = self.real_p*other.real_p - self.imag_p*other.imag_p |
| 26 | + s.imag_p = self.real_p*other.imag_p + self.imag_p*other.real_p |
| 27 | + return s |
| 28 | + |
| 29 | + def __truediv__(self, other): |
| 30 | + s = ComplexNumber() |
| 31 | + s.real_p = (self.real_p*other.real_p + self.imag_p*other.imag_p) / (other.real_p**2 + other.imag_p**2) |
| 32 | + s.imag_p = (self.imag_p*other.real_p - self.real_p*other.imag_p) / (other.real_p**2 + other.imag_p**2) |
| 33 | + return s |
| 34 | + |
| 35 | + def __abs__(self): |
| 36 | + s = ComplexNumber() |
| 37 | + s.real_p = sqrt(self.real_p**2 + self.imag_p**2) |
| 38 | + return s |
| 39 | + |
| 40 | + def __str__(self): |
| 41 | + if self.imag_p >= 0: |
| 42 | + s = "{0:.2f}+{1:.2f}i".format(self.real_p, self.imag_p) |
| 43 | + else: |
| 44 | + s = "{0:.2f}{1:.2f}i".format(self.real_p, self.imag_p) |
| 45 | + return s |
| 46 | + |
| 47 | +x1, y1 = map(float, input().split()) |
| 48 | +x2, y2 = map(float, input().split()) |
| 49 | +z1 = ComplexNumber(x1, y1) |
| 50 | +z2 = ComplexNumber(x2, y2) |
| 51 | +print(z1+z2) |
| 52 | +print(z1-z2) |
| 53 | +print(z1*z2) |
| 54 | +print(z1/z2) |
| 55 | +print(abs(z1)) |
| 56 | +print(abs(z2)) |
0 commit comments