2017-10-21 31 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

是的。会把它放进去。 –