Problem Name: Python - Classes: Dealing with Complex Numbers

Problem Link:   

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





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): = real = imaginary
    def __add__(self, no):
        return Complex(,
    def __sub__(self, no):
        return Complex(,
    def __mul__(self, no):
        re_mul =* -*
        im_mul =* +*
        return Complex(re_mul,im_mul)
    def __truediv__(self, no):
        denominator =**2 +**2
        re_truediv = (* +*
        im_truediv = (* -*
        return Complex(re_truediv,im_truediv)
    def mod(self):
        return Complex(math.sqrt(**2 +**2), 0)
    def __str__(self):
        if == 0:
            result = "%.2f+0.00i" % (
        elif == 0:
            if >= 0:
                result = "0.00+%.2fi" % (
                result = "0.00-%.2fi" % (abs(
        elif > 0:
            result = "%.2f+%.2fi" % (,
            result = "%.2f-%.2fi" % (, abs(
        return result
Copy The Code & Try With Live Editor


[Solved] Triangle Quest in PYTHON solution in Hackerrank
[Solved] Athlete Sort in PYTHON solution in Hackerrank