Skip to main content
 首页 » 编程设计

python之(Python) 确定 (x, y) 坐标是否共线的脚本之出现一些错误

2025年05月04日9pengyingh

如标题所说,我正在尝试编写一个程序,该程序采用 (x, y) 坐标列表,并确定是否有任何 3 个点共线(位于具有相同斜率的直线上)

我收到了一些错误消息。就目前而言,我收到“TypeError:'int'对象不可订阅”消息。如果我取出 collinearityTest 调用 areCollinear 函数的部分,我会收到“索引超出范围”错误。我是 python 的新手,只是想学习。

def areCollinear(p1, p2, p3): 
    slope1 = (p2[1] - p1[1]) / (p2[0] - p1[0]) 
    slope2 = (p3[1] - p2[1]) / (p3[0] - p2[0]) 
    if slope1 == slope2: 
        print "Points are colinear" 
    else: 
        print "Points are NOT colinear, what's the matter with you?" 
 
def collinearityTest(pointList): 
    position = 0 
    while position >=0 and position < len(pointList): 
 
        for p1 in pointList[position]: 
            position = position + 1 
            for p2 in pointList[position]: 
                position = position + 1 
                for p3 in pointList[position]: 
                    position = position + 1 
                    areCollinear(p1, p2, p3) 
 
pointList = [(10, 20), (55, 18), (10, -45.5), (90, 34), (-34, -67), (10, 99)] 
 
collinearityTest(pointList) 

错误信息:

Traceback (most recent call last): 
  File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 23, in <module> 
  File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 19, in collinearityTest 
  File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 2, in areCollinear 
    if __name__ == '__main__': 
TypeError: 'int' object is not subscriptable 

请您参考如下方法:

这里有一个更简单、数值上更稳健和稳定的函数来测试三点的共线性:

def collinear(p0, p1, p2): 
    x1, y1 = p1[0] - p0[0], p1[1] - p0[1] 
    x2, y2 = p2[0] - p0[0], p2[1] - p0[1] 
    return abs(x1 * y2 - x2 * y1) < 1e-12 

(请注意,最好不要对 epsilon 进行硬编码,而是使其与向量的长度相关。)