2017-10-21 71 views
-2

起作用以我的代碼是找到最遠點的算法(可惜在O(N^2)),傳遞元組在Python

from math import sqrt 
INT_MIN = -2147483648 
def distance(a,b): 
    return sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2) 

def process(points): 
    # Function to produce tupple of two farthest Points 
    # currently O(N^2) 
    mx = INT_MIN 
    a,b = (0,0),(0,0) 
    # print points 
    for i in points: 
     for j in points: 
      if i == j: 
       continue 
      if distance(i,j) > mx: 
       mx = distance(i,j) 
       a = i,b = j 
    return (a,b) 

L = [(66, 35), (67, 37), (67, 38), (68, 39)] 
print(process(L)) 

然而,當運行該代碼產生以下錯誤:

Traceback (most recent call last): 
File "./prog.py", line 22, in <module> 
File "./prog.py", line 16, in process 
File "./prog.py", line 4, in distance 
TypeError: 'int' object is not subscriptable 

任何想法如何將元組轉換爲'int'?

+1

你試過把一個'打印(I,J)'在你內心的循環 - 都應該成爲明顯的... –

+0

@喬恩克萊門特我試過了,但我仍然無法找到這樣的任務在邏輯上不正確!不要讓Pythonic的眼睛快速調試:p(開始python幾個月回來) – da6932

回答

6

此行不你在想什麼

a = i,b = j 

嘗試:

a, b = i, j 

a = i 
b = j 

如果使用高階函數,發現的最大距離的細節由max處理 - 功能:

from itertools import combinations 
def process(points): 
    # Function to produce tupple of two farthest Points 
    # currently O(N^2) 
    return max(
     combinations(points, 2), 
     key=lambda (a,b): (a[0] - b[0])**2 + (a[1] - b[1])**2 
    ) 
+0

哇...留下幾乎相同的東西作爲評論...多麼嚇人:p –

+1

@JonClements:這很嚇人?看看我的答案。幾乎在同一時間!甚至同樣! –

+0

說真的......我剛剛在jupyter中打開建議 - 我將開始尋找隱藏的相機:p(max) –

2

您的問題是在聲明

a = i,b = j 

你應該做的卻是,

之一:(大多數人不喜歡這種形式)

a = i;b = j 

或者:

a = i 
b = j 

或者:(首選Python的方式)

a,b = i,j 
+1

是的。會把它放進去。 –