2 min to read

# Classes: Dealing with Complex Numbers - HackerRank Solution Python

Classes: Dealing with Complex Numbers is the medium-level problem of Python on Hackerrank that requires knowledge of the `complex`

function in Python. In this post, you will learn how to solve Hackerrank’s Classes: Dealing with Complex Numbers problem and its solution in Python.

## Problem Statement and Explanation

For the given two complex numbers, perform the arithmetic operations and print the result upto 2 decimal places.

### Input Format

- First value space separated complex numbers, representing
`a + ib`

- Second value space separated complex numbers, representing
`c + id`

## Complex Numbers Solution in Python

## Explanation of Solution

Class called `Complex`

that represents complex numbers. The class has seven methods:

`__init__():`

This method initializes the complex number with the given real and imaginary parts.`__add__():`

This method adds two complex numbers together and returns a new complex number with the result.`__sub__():`

This method subtracts two complex numbers from each other and returns a new complex number with the result.`__mul__():`

This method multiplies two complex numbers together and returns a new complex number with the result.`__truediv__():`

This method divides two complex numbers and returns a new complex number with the result. The class also has two attributes:`__str__()`

method returns a string representation of the complex number in the form a + bi, where a is the real part and b is the imaginary part.`mod()`

method calculates the modulus of the complex number, which is the square root of the sum of the squares of the real and imaginary parts.

`complex`

class has two attributes. These attributes are:

`real:`

This attribute stores the real part of the complex number.`imaginary:`

This attribute stores the imaginary part of the complex number.

The main function of the code creates two complex numbers, `x`

and `y`

, from the user’s input. It then prints the results of the `addition`

, `subtraction`

, `multiplication`

, `division`

, and `modulus`

operations on these two numbers.