HackerRank Solution: Classes - Dealing with complex numbers Python


Hacker Rank Python

Author: Bashir Alam
Reviewer: Deepak Prasad

Question: Dealing with complex numbers – Hacker Rank (Python Classes)

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.

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 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.
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
__mul__ -> Can be overloaded for * operation

 

Possible solutions

Now let us move toward the solutions. We will try to solve the problem using two different methods.

 

Solution-1: Using if-else statements

Here is one possible solution for the question python classes: dealing with complex numbers using if else statement:

import math

# Defining the class
class Complex(object):
    def __init__(self, real, imaginary):
        self.real = real
        self.imaginary = imaginary
        
    def __add__(self, no):
        return Complex(self.real + no.real , self.imaginary + no.imaginary)
        
    def __sub__(self, no):
        return Complex(self.real - no.real , self.imaginary - no.imaginary)       
        
    def __mul__(self, no):
        prod = complex(self.real , self.imaginary)*complex(no.real , no.imaginary)
        return Complex(prod.real , prod.imag)

    def __truediv__(self, no):
        div = complex(self.real , self.imaginary)/complex(no.real , no.imaginary)
        return Complex(div.real , div.imag)


    def mod(self):
        m = math.sqrt(self.real**2 + self.imaginary**2)
        return Complex(m,0)

    def __str__(self):
        if self.imaginary == 0:
            result = "%.2f+0.00i" % (self.real)
        elif self.real == 0:
            if self.imaginary >= 0:
                result = "0.00+%.2fi" % (self.imaginary)
            else:
                result = "0.00-%.2fi" % (abs(self.imaginary))
        elif self.imaginary > 0:
            result = "%.2f+%.2fi" % (self.real, self.imaginary)
        else:
            result = "%.2f-%.2fi" % (self.real, abs(self.imaginary))
        return result
if __name__ == '__main__':
    c = map(float, input().split())
    d = map(float, input().split())
    x = Complex(*c)
    y = Complex(*d)
    print(*map(str, [x+y, x-y, x*y, x/y, x.mod(), y.mod()]), sep='\n')

The __init__ method is the constructor of the class. The __add__ method overloads the + operator and returns a new Complex object that represents the sum of the two complex numbers. The __sub__ method overloads the - operator and returns a new Complex object that represents the difference between the two complex numbers.

 

Solution-2:

Here is another possible solution for the same problem.

import math
class Complex:
    def __init__(self, real, img):
        self.r = real
        self.i = img

    def __str__(self):
        return f'{self.r:.2f}{self.i:+.2f}i'

    def __add__(self, other):
        return Complex(self.r + other.r, self.i + other.i)

    def __sub__(self, other):
        return Complex(self.r - other.r, self.i - other.i)

    def __mul__(self, other):
        real = self.r * other.r - self.i * other.i
        img = self.r * other.i + self.i * other.r
        return Complex(real, img)

    def __truediv__(self, other):
        a, b = self, other
        real = (a.r*b.r + a.i*b.i) / (b.r**2 + b.i**2)
        img = (b.r*a.i - a.r*b.i) / (b.r**2 + b.i**2)
        return Complex(real, img)

    def mod(self):
        # by the way modulus is not a complex num
        return Complex(math.sqrt(self.r ** 2 + self.i ** 2), 0)

if __name__ == '__main__':
    c = map(float, input().split())
    d = map(float, input().split())
    x = Complex(*c)
    y = Complex(*d)
    print(*map(str, [x+y, x-y, x*y, x/y, x.mod(), y.mod()]), sep='\n')

The __init__ method is the constructor of the class. It takes two arguments, real and img, and sets them as the instance variables self.r and self.i respectively. The __str__ method returns a string representation of the complex number in the required format, with a precision of 2 decimal places. The __add__ method overloads the + operator and returns a new Complex object that represents the sum of the two complex numbers. The __sub__ method overloads the - operator and returns a new Complex object that represents the difference between the two complex numbers.

 

Summary

In this article, we solved the "Classes: Dealing with complex numbers" using classes on HackerRank. We solved this problem using two different methods as given above.

 

Further Readings

Question on Hacker Rank: Classes: Dealing with Complex Numbers

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment