Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list of tuples of coordinates in counter-clockwise direction?

Tags:

python

I have a list of tuples having coordinates in (x,y) format. I want to sort/arrange it in counter-clockwise direction. ex:

[(0,1),(3,1),(-1,0),(2,2)]

The arranged list should be:

[(3,1),(2,2),(0,1),(-1,0)]

Note: The list can have 'n' of tuples and (0,0) can be a part of list.

like image 355
SUBHANSHU SAHU Avatar asked Jan 25 '23 21:01

SUBHANSHU SAHU


1 Answers

You could use the 2-argument arctangent to compute the angle from (1, 0) and use that to sort:

>>> vec = [(0,1),(3,1),(-1,0),(2,2)]
>>> sorted(vec, key=lambda p: math.atan2(p[1], p[0]))  # atan2(y, x)
[(3, 1), (2, 2), (0, 1), (-1, 0)]

atan2

(Image courtesy of Wikipedia.)

like image 121
NPE Avatar answered Jan 29 '23 15:01

NPE