
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- Python program to sort table based on given attribute index
- Program to sort out phrases based on their appearances in Python
- Program to sort an array based on the parity values in Python
- C program to sort triangles based on area
- Program to sort numbers based on 1 count in their binary representation in Python
- Python program to sort matrix based upon sum of rows
- Sort tuple based on occurrence of first element in Python
- Plot scatter points on polar axis in Matplotlib
- Program to perform bubble sort based on choice in 8085 Microprocessor
- Plot a polar color wheel based on a colormap using Python/Matplotlib
- a 8085 Program to perform bubble sort based on choice
- Python program to convert a list to a set based on a common element
- C# Program to Sort a List of Employees Based on Salary using LINQ
- 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

Advertisements