迭代坐标数组时出错:“0”;类型错误:';浮动';“对象不可编辑”;(python)
我的程序应该计算最近一对的距离。它接受两个排序数组:xpts是按x坐标排序的对/坐标数组。ypts是按y坐标排序的数组。我试图使用分治技术,所以我递归地传入数组的一半。然而,我得到了一个错误 我的代码是:迭代坐标数组时出错:“0”;类型错误:';浮动';“对象不可编辑”;(python),python,compiler-errors,Python,Compiler Errors,我的程序应该计算最近一对的距离。它接受两个排序数组:xpts是按x坐标排序的对/坐标数组。ypts是按y坐标排序的数组。我试图使用分治技术,所以我递归地传入数组的一半。然而,我得到了一个错误 我的代码是: def closest_pair(xpts,ypts): if xpts size < = 3: if xsize==1: return xpts[0][0] elif xsize==2: return dist(xpts[0],xpt
def closest_pair(xpts,ypts):
if xpts size < = 3:
if xsize==1:
return xpts[0][0]
elif xsize==2:
return dist(xpts[0],xpts[1])
else:
one= xpts[0]
two= xpts[1]
three= xpts[2]
s1= dist(one,two)
s2= dist(two,three)
s3= dist(one,three)
s= (min(s1,s2,s3),min(xpts[0],xpts[1],xpts[2]))
return s
else:
...
xlft= xpts[:xsize/2]
xrht= xpts[(xsize/2)+1:]
ylft= []
yrht= []
median= xpts[(xsize/2)-1][0]
for p in ypts:
if p[0] <= median:
ylft.append(p)
else:
yrht.append(p)
a1, pair1= closest_pair(xlft,ylft)
a2, pair2= closest_pair(xrht,yrht)
st= []
if a1 < a2:
a3, pair3= (a1,pair1)
else:
a3, pair3= (a2,pair2)
for p in ypts:
if abs(p[0]-median) < a3:
st.append(p)
n_st= len(st)
closest= (a3,pair3)
if n_st>1:
for i in range(n_st-1):
for j in range(i+1,min(i+8,n_st)):
if dist(st[i],st[j]) < closest[0]:
closest= (dist(st[i],st[j]),(st[i],st[j]))
d= closest
return d
d1 = closest_pair(xpts, ypts)[0]
print d1
def最近的_对(xpts、ypts):
如果xpts大小<=3:
如果xsize==1:
返回xpts[0][0]
elif xsize==2:
返回区(xpts[0],xpts[1])
其他:
1=xpts[0]
二=xpts[1]
三=xpts[2]
s1=距离(一,二)
s2=距离(二,三)
s3=距离(一,三)
s=(最小值(s1,s2,s3),最小值(xpts[0],xpts[1],xpts[2]))
返回s
其他:
...
xlft=xpts[:xsize/2]
xrht=xpts[(xsize/2)+1:]
ylft=[]
yrht=[]
中位数=xpts[(xsize/2)-1][0]
对于展翅计划中的p:
如果p[0]1:
对于范围内的i(n_st-1):
对于范围内的j(i+1,min(i+8,n_st)):
如果距离(st[i],st[j])<最近的[0]:
最近的=(距离(st[i],st[j]),(st[i],st[j]))
d=最近的
返回d
d1=最近的_对(xpts,ypts)[0]
打印d1
最近的\u对
返回一个浮点,所以
a1, pair1= closest_pair(xlft,ylft)
将导致异常。这称为序列解包,并尝试迭代最近的_对(xlft,ylft)
回溯包括异常的行号。如果您可以包含一个标记(例如#
您正在返回一个浮点值。这就是导致错误的原因
假设您有一个坐标元组列表,并将其索引到列表中,然后元组会给您一个无法迭代的浮点值。因此,消息就是这样。如果xpts size<=3:bruteforce distance
。这条线在做什么?名称之间如何有空格?这是如果x arra的大小为y小于/等于3,我手动计算距离并返回它。你能粘贴你一直在使用的代码来代替伪代码吗?因为这是返回基本情况的代码,这是导致错误的原因。@Marek,这是序列解包a1,pair1=最近的_对(xlft,ylft)
当最近的\u对
返回一个floatThank you!修复了它:)
a1, pair1= closest_pair(xlft,ylft)
if xsize==1:
return xpts[0][0]