In this HackerRank Classes: Dealing with Complex Numbers problem 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 parts should be correct up to two decimal places.

HackerRank Classes: Dealing with Complex Numbers in python problem solution

 HackerRank Classes: Dealing with Complex Numbers in python problem solution

# Enter your code here. Read input from STDIN. Print output to STDOUT
import math
class complex():
    def __init__(self,x,y):
        self.x = float(x)
        self.y = float(y)
    def __str__(self):
        if self.x == 0 and self.y == 0:
            return "0.00"
        a = '{0:.2f}'.format(float(self.x))
        b = '{0:.2f}'.format(float(self.y))+"i"
        if self.x == 0:
            return b
        elif self.y == 0:
            return a
        elif self.y > 0:
            b = '+ '+b
        else:
            b = '- '+b[1:]
        return a + " " + b
    def __add__(self,b):
        return complex(self.x+b.x,self.y+b.y)
    def __radd__(self,b):
        return complex(self.x+b.x,self.y+b.y)
    def __sub__(self,b):
        return complex(self.x-b.x,self.y-b.y)
    def __rsub__(self,b):
        return complex(b.x-self.x,b.y-self.y)
    def __mul__(self,b):
        i = (self.x*b.y) + (self.y*b.x)
        r = self.x*b.x -(self.y*b.y)
        return complex(r,i)
    def __rmul__(self,b):
        return __mul__(b)
    def invert(self):
        return complex(self.x,(-1)*self.y)
    def mod(self):
        return '{0:.2f}'.format(math.sqrt(self.x**2 + self.y**2))
    def __div__(self,b):
        bottom = (b*b.invert()).x
        #print bottom
        top = (self*b.invert())
        r = top.x/bottom
        i = top.y/bottom
        return complex(r,i)
    
a = raw_input().strip().split()
b = raw_input().strip().split()
a = complex(*a)
b = complex(*b)

print str(a + b)
print str(a - b)
print str(a * b)
print str(a / b)
print a.mod()
print b.mod()