use*_*457 1 python graph function list points
就像标题所说的那样,我正在尝试编写一个带有(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)
Run Code Online (Sandbox Code Playgroud)
错误信息:
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
Run Code Online (Sandbox Code Playgroud)
这是一个更简单,数值更强大,更稳定的函数来测试三点的共线性:
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
Run Code Online (Sandbox Code Playgroud)
(注意,最好不要对epsilon进行硬编码,并使其相对于向量的长度.)