# Program to sort given set of Cartesian points based on polar angles in Python

Suppose we have a set of Cartesian points in a list called points. We have to sort them based on their polar angles. The polar angles vary in range 0 and 2*PI. If some points have same polar angles, then arrange them based on the distance of that point from the origin.

So, if the input is like points = [(1,1), (1,-2),(-2,2),(5,4),(4,5),(2,3),(-3,4)],

then the output will be [(5, 4), (1, 1), (4, 5), (2, 3), (-3, 4), (-2, 2), (1, -2)]

To solve this, we will follow these steps −

• Define a comparator function key() . This will take x
• atan := tan-inverse of x[1]/x[0]
• return pair (atan, x[1]^2+x[0]^2) if atan >= 0 otherwise (2*pi + atan, x[0]^2+x[1]^2)
• then sort points using comparator function key()

## Example

Let us see the following implementation to get better understanding −

import math
def solve(points):
def key(x):
atan = math.atan2(x[1], x[0])
return (atan, x[1]**2+x[0]**2) if atan >= 0 else (2*math.pi + atan, x[0]**2+x[1]**2)

return sorted(points, key=key)

points = [(1,1), (1,-2),(-2,2),(5,4),(4,5),(2,3),(-3,4)]
print(solve(points))

## Input

[(1,1), (1,-2),(-2,2),(5,4),(4,5),(2,3),(-3,4)]


## Output

[(5, 4), (1, 1), (4, 5), (2, 3), (-3, 4), (-2, 2), (1, -2)]

Advertisements
{"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}