在 Python 中根据极角对给定的笛卡尔点集进行排序的程序

假设我们在称为点的列表中有一组笛卡尔点。我们必须根据它们的极角对它们进行分类。极角在 0 和 2*PI 范围内变化。如果某些点具有相同的极角,则根据该点与原点的距离来排列它们。

所以,如果输入像点 = [(1,1), (1,-2),(-2,2),(5,4),(4,5),(2,3),(- 3,4)],

那么输出将是 [(5, 4), (1, 1), (4, 5), (2, 3), (-3, 4), (-2, 2), (1, -2) ]

示例

让我们看看以下实现以更好地理解 -

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

输入

[(1,1), (1,-2),(-2,2),(5,4),(4,5),(2,3),(-3,4)]
输出结果
[(5, 4), (1, 1), (4, 5), (2, 3), (-3, 4), (-2, 2), (1, -2)]

猜你喜欢