HackerRank Python - Classes: Dealing with Complex Numbers




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.



  1. import math
  2. class Complex(object):
  3. def __init__(self, real, imaginary):
  4. self.real = real
  5. self.imaginary = imaginary
  6. def __add__(self, no):
  7. a = self.real
  8. b = self.imaginary
  9. c = no.real
  10. d = no.imaginary
  11. return Complex(a + c, b + d)
  12. def __sub__(self, no):
  13. a = self.real
  14. b = self.imaginary
  15. c = no.real
  16. d = no.imaginary
  17. return Complex(a - c, b - d)
  18. def __mul__(self, no):
  19. a = self.real
  20. b = self.imaginary
  21. c = no.real
  22. d = no.imaginary
  23. real_mult = (a * c) - (b * d)
  24. imag_mult = (a * d) + (b * c)
  25. return Complex(real_mult, imag_mult)
  26. def __truediv__(self, no):
  27. a = self.real
  28. b = self.imaginary
  29. c = no.real
  30. d = no.imaginary
  31. real_numerator = a * c + b * d
  32. imag_numerator = b * c - a * d
  33. denom = c * c + d * d
  34. real_div = real_numerator / denom
  35. imag_div = imag_numerator / denom
  36. return Complex(real_div, imag_div)
  37. def mod(self):
  38. a = self.real
  39. b = self.imaginary
  40. return Complex(math.sqrt(a ** 2 + b ** 2), 0)
  41. def __str__(self):
  42. if self.imaginary == 0:
  43. result = '%.2f+0.00i' % (self.real)
  44. elif self.real == 0:
  45. if self.imaginary >= 0:
  46. result = '0.00+%.2fi' % (self.imaginary)
  47. else:
  48. result = '0.00-%.2fi' % (abs(self.imaginary))
  49. elif self.imaginary > 0:
  50. result = '%.2f+%.2fi' % (self.real, self.imaginary)
  51. else:
  52. result = '%.2f-%.2fi' % (self.real, abs(self.imaginary))
  53. return result
  54. if __name__ == '__main__':
  55. c = map(float, input().split())
  56. d = map(float, input().split())
  57. x = Complex(*c)
  58. y = Complex(*d)
  59. print(*map(str, [x+y, x-y, x*y, x/y, x.mod(), y.mod()]), sep='\n')
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution






codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube