我一直在尝试在 Python 中实现礼品包装算法,我目前有以下代码:
def createIslandPolygon(particleCoords):
startPoint = min(particleCoords.iteritems(),key = lambda x: x[1][1])[1]
check = 1
islandPolygon = []
particleList = []
for key in particleCoords:
particleList.append(particleCoords[key])
currentPoint = startPoint
while(currentPoint != startPoint or check == 1):
islandPolygon.append(currentPoint)
check = 0
angleDict = {}
angleList = []
for point in particleList:
if point != currentPoint:
angleDict[(angleBetweenTwoPoints(currentPoint, point))] = point
angleList.append(angleBetweenTwoPoints(currentPoint, point))
smallestAngle = min(angleList)
currentPoint = angleDict[smallestAngle]
return islandPolygon
并用于计算极坐标:
def angleBetweenTwoPoints(p1, p2):
p3 = (p1[0], p1[1] + 2)
a = (p1[0] - p2[0], p1[1] - p2[1])
b = (p1[0] - p3[0], p1[1] - p3[1])
theta = ((a[0]*b[0]) + (a[1]*b[1]))
theta = theta / (sqrt((a[0]*a[0]) + (a[1]*a[1])) * sqrt((b[0]*b[0]) + (b[1]*b[1])))
theta = math.acos(theta)
return theta
问题是代码似乎永远不会离开 while 循环,我不知道为什么。有谁有想法吗?
谢谢。
(是的,代码很粗制滥造,我只是快速将它们拼凑在一起)
编辑:打印出坐标似乎表明它们只在两个坐标之间跳跃。