Algorithm
Problem Name: Python -
In this HackerRank Functions in PYTHON 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 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 C and D, the output should be in the following sequence on separate lines:
- C + D
- C - D
- C * D
- C / D
- mod(C)
- mod(D)
For complex numbers with non-zero real (A) and complex part (B) ,the output should be in the following format:
A + Bi
Replace the plus symbol(+) with a minus symbol (-) when B < 0.
For complex numbers with a zero complex part i.e. real numbers, the output should be:
A + 0.00i
For complex numbers where the real part is zero and the complex part(B) is non-zero, the output should be:
0.00 + Bi
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.
Code Examples
#1 Code Example with Python Programming
Code -
Python Programming
class Complex(object):
def __init__(self, real, imaginary):
self.re = real
self.im = imaginary
def __add__(self, no):
return Complex(self.re+no.re, self.im+no.im)
def __sub__(self, no):
return Complex(self.re-no.re, self.im-no.im)
def __mul__(self, no):
re_mul = self.re*no.re - self.im*no.im
im_mul = self.re*no.im + self.im*no.re
return Complex(re_mul,im_mul)
def __truediv__(self, no):
denominator = no.re**2 + no.im**2
re_truediv = (self.re*no.re + self.im*no.im)/denominator
im_truediv = (self.im*no.re - self.re*no.im)/denominator
return Complex(re_truediv,im_truediv)
def mod(self):
return Complex(math.sqrt(self.re**2 + self.im**2), 0)
def __str__(self):
if self.im == 0:
result = "%.2f+0.00i" % (self.re)
elif self.re == 0:
if self.im >= 0:
result = "0.00+%.2fi" % (self.im)
else:
result = "0.00-%.2fi" % (abs(self.im))
elif self.im > 0:
result = "%.2f+%.2fi" % (self.re, self.im)
else:
result = "%.2f-%.2fi" % (self.re, abs(self.im))
return result
Copy The Code &
Try With Live Editor