我有 2 个列表包含两组红色和蓝色点.我还有一个包含行的列表.我必须确定这条线是否分开


import re
Red= [(1,1),(2,1),(4,2),(2,4), (-1,4)]
Blue= [(-2,-1),(-1,-2),(-3,-2),(-3,-1),(1,-3)]
Lines=["1x+1y+0","1x-1y+0","1x+0y-3","0x+1y-0.5"]
ls=[]
red_dist=[]
blue_dist=[]
def sep(ls):
for line in Lines:
a=[float(coef.strip()) for coef in re.split('x|y',line)]
ls.append(a)
print(a)
for i in ls:
for point in Red:
red_dist.append(float(i[0]*point[0]+(float(i[1])*point[1])+float(i[2])))
for points in Blue:
blue_dist.append(float(i[0]*points[0]+(float(i[1])*points[1])+float(i[2])))
for i in ls:
for x in red_dist:
for y in blue_dist:
if((x>0 and y<0) or (y>0 and x<0)):
return True
else:
return False
sep(ls)

输出:

True

预期产出:

True
False
False
True

为什么我的程序没有循环?

我确实认为您的编程是循环的,只是外部看不到任何内容。然后它到达最后一个循环,但这个循环要么返回 True,要么返回 False。在这两种情况下,函数都会返回而不完成该循环。

尝试使用 print(( 语句而不是返回值,会发生很多事情。对代码中发生的情况使用一些临时打印语句总是一个好主意。

你的代码实际上是循环的。您无法看到它,因为每当执行到达条件时。要么 if 要么 else 总是如此,它将根据第一次迭代本身的条件返回 true 或 false。

for i in ls:
for x in red_dist:
for y in blue_dist:
if((x>0 and y<0) or (y>0 and x<0)):
return True
else:
return False

因此,您看到的输出是第一次迭代的。只需将 return 替换为打印件,如下所示即可观察所有结果:

if((x>0 and y<0) or (y>0 and x<0)):
print(True)
else:
print(False)

最新更新