HackerRank Python: Polar Coordinates Solution

Question

To see the complete question Please visit : 

Polar Coordinates

Task
You are given a complex z. Your task is to convert it to polar coordinates.

Input Format

A single line containing the complex number z. Note: complex() function can be used in python to convert the input as a complex number.

Constraints

Given number is a valid complex number

Output Format

The first line should contain the value of γ.

The second line should contain the value of φ.

Sample Input

  1+2j

Sample Output

 2.23606797749979 
 1.1071487177940904

Note: The output should be correct up to 3 decimal places.

Solution

				
					# Enter your code here. Read input from STDIN. Print output to STDOUT
import cmath

n = input()
print(abs(complex(n)))
print(cmath.phase(complex(n)))
                        
				
			
  1. The code begins by importing the cmath module. This module provides mathematical functions for complex numbers.

  2. The next line of code reads an input value using the input() function. It is assumed that the input is a complex number represented as a string.

  3. The complex() function is used to convert the input string into a complex number. The complex() function takes a string representation of a complex number as an argument and returns a complex number object.

  4. The abs() function is then used to calculate the absolute value (magnitude) of the complex number. It returns a floating-point value representing the distance from the origin (0) to the complex number in the complex plane.

  5. The result of the abs() function is printed using the print() function.

  6. The cmath.phase() function is used to calculate the phase angle of the complex number. The phase angle represents the angle between the positive real axis and the vector representing the complex number in the complex plane. The cmath.phase() function returns the phase angle in radians.

  7. The result of the cmath.phase() function is printed using the print() function.

If you find anything wrong in this Solution, feel free to reach us in the comment section.

Sharing Is Caring:

5 thoughts on “HackerRank Python: Polar Coordinates Solution”

Leave a Comment