- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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)]

- Related Questions & Answers
- Python program to sort table based on given attribute index
- Plot scatter points on polar axis in Matplotlib
- Program to sort out phrases based on their appearances in Python
- C program to sort triangles based on area
- Program to sort an array based on the parity values in Python
- Plot a polar color wheel based on a colormap using Python/Matplotlib
- Sort tuple based on occurrence of first element in Python
- Python program to sort matrix based upon sum of rows
- Program to sort numbers based on 1 count in their binary representation in Python
- a 8085 Program to perform bubble sort based on choice
- Program to perform bubble sort based on choice in 8085 Microprocessor
- Count of obtuse angles in a circle with ‘k' equidistant points between 2 given points in C++
- C++ Program to Check if a Given Set of Three Points Lie on a Single Line or Not
- Sort HashMap based on keys in Java
- Python program to convert a list to a set based on a common element

Advertisements