2013-05-08 134 views
-1

我的程序應該計算最接近的對的距離。它接受兩個排序數組:xpts是一個由x座標排序的對/座標數組。 ypts是一個按y座標排序的數組。我試圖使用分而治之的技術,所以我遞歸地傳遞數組的一半。但是,我收到一個錯誤。迭代座標數組時出錯:「TypeError:'float'對象不可迭代」(python)

TypeError: 'float' object is not iterable: a1, pair1= closest_pair(xlft,ylft) 

我的代碼是:

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 
+0

'if xpts size <= 3:bruteforce distance'。這條線是幹什麼的?名稱之間有什麼空格? – 2013-05-08 04:13:03

+0

如果x數組的大小小於/等於3,則僞代碼,我手動計算距離並返回它。 – Hon 2013-05-08 04:15:55

+1

您可以粘貼您使用的代碼代替僞代碼嗎?因爲這是返回一些基本情況並導致錯誤的代碼。 – 2013-05-08 04:16:44

回答

2
if xsize==1: 
     return xpts[0][0] 

您在這裏返回浮動。這是導致錯誤的原因。

推測,你有一個座標元組列表和索引列表,然後元組給你一個float不能迭代。因此,消息。

+0

謝謝!它修正了:) – Hon 2013-05-08 04:27:49

0

closest_pair返回一個浮點數,所以

a1, pair1= closest_pair(xlft,ylft) 

將導致異常。這稱爲序列解包,並嘗試迭代closest_pair(xlft,ylft)的值

回溯包括行號的異常。這將是最有幫助的,如果你能包括標記(如#<== exception here)對應的行拋出異常