传递元组在Python中运行

时间:2017-10-21 18:53:41

标签: python

在我的代码中是一个找到最远点的算法(遗憾地在O(N ^ 2)中),

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'的吗?

2 个答案:

答案 0 :(得分: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
    )

答案 1 :(得分:2)

您的问题出在声明中

a = i;b = j

你应该做的是,

(大多数人不喜欢这种形式)

a = i
b = j

或者:

a,b = i,j

或者:(首选pythonic方式)

{{1}}