4

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.

  • For a more generalized solution you can refer to: https://stackoverflow.com/questions/7673492/how-to-order-points-anti-clockwise – blhsing Sep 04 '19 at 07:48

1 Answers1

8

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.)

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 1
    This works only if (0, 0) happens to be the center point of the given coordinates. – blhsing Sep 04 '19 at 07:09
  • 2
    @blhsing: Do you have reasons to think that (0, 0) is not what OP requires? If so, I can trivially edit the answer to shift the coordinate system (all it takes is two subtractions in the lambda). – NPE Sep 04 '19 at 07:12
  • The reason is simply that the given sample points do not have (0, 0) as the center point; therefore the calculation should be generalized and not based on the assumption that (0, 0) is the center point. – blhsing Sep 04 '19 at 07:16
  • @blhsing Sorry, you completely lost me there. The way I read the question is that (0, 0) is precisely the origin of the coordinate system around which the "counter-clockwise direction" is defined. Perhaps the OP could confirm one way or the other? I'm happy to delete or fix the answer if it's answering the wrong question (which I don't right now believe it does). – NPE Sep 04 '19 at 07:19
  • The way I interpret sorting a set of coordinates counter-clockwise is such that, when pointed to from the center point, the vectors to those ordered points rotate counter-clockwise. I now see that you're simply assuming that they're always pointed to from (0, 0). I suppose that's also a possible way to interpret the question given the lack of details from the OP, although I still think it's more likely than not that the OP means to sort them from the center point. – blhsing Sep 04 '19 at 07:30
  • @NPE, I am getting syntax error while trying your answer ```sorted(vec, key=lambda (x, y): math.atan2(y, x)) ^ SyntaxError: invalid syntax``` – SUBHANSHU SAHU Sep 04 '19 at 07:39
  • @SUBHANSHUSAHU: Forgot about Python3, sorry. Should be fixed now. – NPE Sep 04 '19 at 07:42
  • @NPE, This solution doesn't work if (0,0) is included in list of tuples – SUBHANSHU SAHU Sep 05 '19 at 14:31