-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathclass-1-dealing-with-complex-numbers.py
54 lines (45 loc) · 1.78 KB
/
class-1-dealing-with-complex-numbers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# Python > Classes > Classes: Dealing with Complex Numbers
# Create a new data type for complex numbers.
#
# https://www.hackerrank.com/challenges/class-1-dealing-with-complex-numbers/problem
#
import math
# (skeliton_head) ----------------------------------------------------------------------
class Complex(object):
def __init__(self, real, imaginary):
self.a = real
self.b = imaginary
def __add__(self, no):
return Complex(self.a + no.a, self.b + no.b)
def __sub__(self, no):
return Complex(self.a - no.a, self.b - no.b)
def __mul__(self, no):
# (a+ib)(c+id) = (ac-bd) + (ad+bc)i
return Complex(self.a * no.a - self.b * no.b, self.a * no.b + self.b * no.a)
def __truediv__(self, no):
# (a+ib)/(c+id) = (a+ib)*(c-id) /((c+id)(c-id))
# = (ac+bd+(bc-ad)i)/(c*c+d*d)
x = no.a ** 2 + no.b ** 2
return Complex((self.a * no.a + self.b * no.b) / x, (self.b * no.a - self.a * no.b) / x)
def mod(self):
return Complex(math.sqrt(self.a ** 2 + self.b ** 2), 0)
def __str__(self):
if self.b == 0:
result = "%.2f+0.00i" % (self.a)
elif self.a == 0:
if self.b >= 0:
result = "0.00+%.2fi" % (self.b)
else:
result = "0.00-%.2fi" % (abs(self.b))
elif self.b > 0:
result = "%.2f+%.2fi" % (self.a, self.b)
else:
result = "%.2f-%.2fi" % (self.a, abs(self.b))
return result
# (skeliton_tail) ----------------------------------------------------------------------
if __name__ == '__main__':
c = map(float, input().split())
d = map(float, input().split())
x = Complex(*c)
y = Complex(*d)
print(*map(str, [x+y, x-y, x*y, x/y, x.mod(), y.mod()]), sep='\n')