Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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. We need to sort them based on their polar angles, which vary between 0 and 2?. If points have the same polar angles, we arrange them by their distance from the origin.
For example, if we have points = [(1,1), (1,-2), (-2,2), (5,4), (4,5), (2,3), (-3,4)], the output will be [(5, 4), (1, 1), (4, 5), (2, 3), (-3, 4), (-2, 2), (1, -2)].
Algorithm
To solve this problem, we follow these steps ?
- Define a key function that calculates the polar angle using
atan2() - For each point, compute the angle and distance from origin
- Return a tuple (angle, distance) for sorting
- If angle is negative, add 2? to normalize it to [0, 2?] range
- Sort points using this key function
Example
Let us see the implementation to understand better ?
import math
def solve(points):
def key(x):
atan = math.atan2(x[1], x[0])
distance = x[1]**2 + x[0]**2
return (atan, distance) if atan >= 0 else (2*math.pi + atan, distance)
return sorted(points, key=key)
points = [(1,1), (1,-2), (-2,2), (5,4), (4,5), (2,3), (-3,4)]
result = solve(points)
print("Original points:", points)
print("Sorted by polar angle:", result)
Original points: [(1, 1), (1, -2), (-2, 2), (5, 4), (4, 5), (2, 3), (-3, 4)] Sorted by polar angle: [(5, 4), (1, 1), (4, 5), (2, 3), (-3, 4), (-2, 2), (1, -2)]
How It Works
The math.atan2(y, x) function returns the angle in radians between the positive x-axis and the point (x, y). This handles all quadrants correctly and returns values in the range [-?, ?]. We normalize negative angles by adding 2? to get the range [0, 2?].
When two points have the same polar angle, the secondary sort criterion is the distance from origin (x² + y²), ensuring closer points appear first.
Conclusion
This solution uses atan2() to calculate polar angles and sorts points counter-clockwise from the positive x-axis. Points with identical angles are ordered by their distance from the origin.
