Hackerrank Classes: Dealing with Complex Numbers Solution
For this challenge, you are given two complex numbers, and you have to print the result of their addition, subtraction, multiplication, division and modulus operations.
The real and imaginary precision part should be correct up to two decimal places.
Input Format
One line of input: The real and imaginary part of a number separated by a space.
Output Format
For two complex numbers and , the output should be in the following sequence on separate lines:
For complex numbers with non-zero real and complex part, the output should be in the following format:
Replace the plus symbol with a minus symbol when .
For complex numbers with a zero complex part i.e. real numbers, the output should be:
For complex numbers where the real part is zero and the complex part is non-zero, the output should be:
Sample Input
2 1
5 6
Sample Output
7.00+7.00i
-3.00-5.00i
4.00+17.00i
0.26-0.11i
2.24+0.00i
7.81+0.00i
Concept
Python is a fully object-oriented language like C++, Java, etc. For reading about classes, refer here.
Methods with a double underscore before and after their name are considered as built-in methods. They are used by interpreters and are generally used in the implementation of overloaded operators or other built-in functionality.
__add__-> Can be overloaded for + operation
__sub__ -> Can be overloaded for - operation
For more information on operator overloading in Python, refer here
Solution in python3
Approach 1.
parts = list(map(float, input().split()))
a = complex(parts[0], parts[1])
parts = list(map(float, input().split()))
b = complex(parts[0], parts[1])
def p(comp):
if comp.real != 0 and comp.imag != 0:
print('%.2f %s %.2fi' % (comp.real, '+' if comp.imag >= 0 else '-', abs(comp.imag)))
elif comp.imag == 0:
print("%.2f" % comp.real)
elif comp.real == 0:
print("%.2fi" % comp.imag)
p(a+b)
p(a-b)
p(a*b)
p(a/b)
print("%.2f" % abs(a))
print("%.2f" % abs(b))
Approach 2.
p = list(map(float, input().split()))
A = p[0] + p[1] * 1j
p = list(map(float, input().split()))
B = p[0] + p[1] * 1j
def printc(A):
sign = ""
if A.imag >= 0:
sign = "+"
else:
sign = "-"
if A.imag == 0:
print("%.2f" % A.real)
elif A.real != 0:
print("%.2f" % A.real, sign, "%.2fi" % abs(A.imag))
else:
print("%.2fi" % A.imag)
printc(A + B)
printc(A - B)
printc(A * B)
printc(A / B)
print("%.2f" % abs(A))
print("%.2f" % abs(B))
Approach 3.
import sys
def output(num):
real = num.real
imag = num.imag
if real == 0 and imag == 0:
print('0.00')
elif real == 0:
print('{:.2f}i'.format(imag))
elif imag == 0:
print('{:.2f}'.format(real))
else:
print('{:.2f} {} {:.2f}i'.format(real, '-' if imag < 0 else '+', abs(imag)))
real1, imag1 = [float(x) for x in input().split()]
real2, imag2 = [float(x) for x in input().split()]
C1 = complex(real1, imag1)
C2 = complex(real2, imag2)
output(C1 + C2)
output(C1 - C2)
output(C1 * C2)
output(C1 / C2)
print('{:.2f}'.format(abs(C1)))
print('{:.2f}'.format(abs(C2)))
Solution in python
Approach 1.
import math
def get_num():
return map(float, raw_input().strip().split())
c = get_num()
d = get_num()
def output(a, b):
sa = "%.2f" % (a,)
sb = "%.2f" % (abs(b),)
if 0 == b:
print sa
elif 0 == a:
print "%.2fi" % (b,)
else:
c = "+"
if b < 0:
c = "-"
print "%s %s %si" % (sa, c, sb)
def mod(lst):
return math.sqrt(lst[0]*lst[0] + lst[1]*lst[1])
output(c[0]+d[0], c[1]+d[1])
output(c[0]-d[0], c[1]-d[1])
output(c[0]*d[0] - c[1]*d[1], c[0]*d[1] + c[1]*d[0])
output((c[0]*d[0] + c[1]*d[1])/(mod(d) * mod(d)), (- c[0]*d[1] + c[1]*d[0])/(mod(d) * mod(d)))
output(mod(c), 0)
output(mod(d), 0)
Approach 2.
import math
class Complex:
def __init__(self, re, im):
self.re = re
self.im = im
def mod(self):
return math.sqrt(self.re*self.re + self.im*self.im)
def __add__(self, c2):
return Complex(self.re + c2.re, self.im + c2.im)
def __sub__(self, c2):
return Complex(self.re - c2.re, self.im - c2.im)
def __mul__(self, c2):
return Complex(self.re*c2.re - self.im*c2.im, self.im*c2.re + self.re*c2.im)
def __div__(self, c2):
c2_mod2 = float(c2.re*c2.re + c2.im*c2.im)
return Complex((self.re*c2.re + self.im*c2.im)/c2_mod2,
(self.im*c2.re - self.re*c2.im)/c2_mod2);
def conjugate(self):
return Complex(self.re, -self.im)
def __str__(self):
if self.im == 0:
return '%.2f' % self.re
if self.re == 0:
return '%.2fi' % self.im
if self.im > 0:
return '%.2f + %.2fi' % (self.re, self.im)
else:
return '%.2f - %.2fi' % (self.re, -self.im)
line = raw_input().split(' ')
c1 = Complex(float(line[0]), float(line[1]))
line = raw_input().split(' ')
c2 = Complex(float(line[0]), float(line[1]))
print c1 + c2
print c1 - c2
print c1 * c2
print c1 / c2
print '%.2f' % c1.mod()
print '%.2f' % c2.mod()
Approach 3.
# Enter your code here. Read input from STDIN. Print output to STDOUT
import math
class Calc(object):
def __init__(self,r,i):
self.r = r
self.i = i
[a,b] = [float(j) for j in raw_input().split()]
A = Calc(a,b)
[a,b] = [float(j) for j in raw_input().split()]
B = Calc(a,b)
#Addition
addr = (A.r+B.r)
addi = (A.i+B.i)
if addi == 0:
print "%.2f"%addr
elif addr == 0:
print "%.2fi"%addi
else:
if addi > 0:
print "%.2f"%addr+" + "+"%.2fi"%addi
else:
print "%.2f"%addr+" - "+"%.2fi"%(addi*-1)
#Subtraction
addr = (A.r-B.r)
addi = (A.i-B.i)
if addi == 0:
print "%.2f"%addr
elif addr == 0:
print "%.2fi"%addi
else:
if addi > 0:
print "%.2f"%addr+" + "+"%.2fi"%addi
else:
print "%.2f"%addr+" - "+"%.2fi"%(addi*-1)
#Multiplication
addr = (A.r*B.r - A.i*B.i)
addi = (A.r*B.i+B.r*A.i)
if addi == 0:
print "%.2f"%addr
elif addr == 0:
print "%.2fi"%addi
else:
if addi > 0:
print "%.2f"%addr+" + "+"%.2fi"%addi
else:
print "%.2f"%addr+" - "+"%.2fi"%(addi*-1)
#Division
addr = (A.r*B.r + A.i*B.i)/(B.r**2 + B.i**2)
addi = (B.r*A.i - A.r*B.i)/(B.r**2 + B.i**2)
if addi == 0:
print "%.2f"%addr
elif addr == 0:
print "%.2fi"%addi
else:
if addi > 0:
print "%.2f"%addr+" + "+"%.2fi"%addi
else:
print "%.2f"%addr+" - "+"%.2fi"%(addi*-1)
#Mod
print "%.2f"%math.sqrt(A.r**2+A.i**2)
print "%.2f"%math.sqrt(B.r**2+B.i**2)