Python“循环法”
给定多个 (x,y) 有序对,我想比较它们之间的距离。 因此,假设我有一个有序对列表:
pairs = [a,b,c,d,e,f]
我有一个函数,它接受两个有序对并找到它们之间的距离:
def distance(a,b):
from math import sqrt as sqrt
from math import pow as pow
d1 = pow((a[0] - b[0]),2)
d2 = pow((a[1] - b[1]),2)
distance = sqrt(d1 + d2)
return distance
如何使用此函数将每个有序对与每个其他有序对进行比较,最终找到两个有序对他们之间的距离最大?
Psuedopsuedocode:
distance(a,b)
distance(a,c)
...
distance(e,f)
任何帮助将不胜感激。
Given multiple (x,y) ordered pairs, I want to compare distances between each one of them.
So pretend I have a list of ordered pairs:
pairs = [a,b,c,d,e,f]
I have a function that takes two ordered pairs and find the distance between them:
def distance(a,b):
from math import sqrt as sqrt
from math import pow as pow
d1 = pow((a[0] - b[0]),2)
d2 = pow((a[1] - b[1]),2)
distance = sqrt(d1 + d2)
return distance
How can I use this function to compare every ordered pair to every other ordered pair, ultimately finding the two ordered-pairs with the greatest distance between them?
Psuedopsuedocode:
distance(a,b)
distance(a,c)
...
distance(e,f)
Any help would be tremendously appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 python 2.6 中,您可以使用 itertools.permutations
或
in python 2.6, you can use itertools.permutations
or
尝试:
这可以避免身份比较(例如,距离(x,x),距离(y,y)等)。 它还避免了进行对称比较,因为
distance(x, y) == distance(y, x)
。更新:我喜欢Evgeny的解决方案 更好地使用
itertools
,因为它更简洁地表达了您想要做的事情。 我们的两种解决方案都做同样的事情。 (注意:确保您使用组合,而不是排列——那样会慢很多!)Try:
This avoid identity-comparisons (e.g.
distance(x, x)
,distance(y, y)
, etc.). It also avoids doing symmetric comparisons, sincedistance(x, y) == distance(y, x)
.Update: I like Evgeny's solution to use
itertools
a little better, as it expresses what you're trying to do more succinctly. Both of our solutions do the same thing. (Note: make sure you use combinations, not permutations -- that will be much slower!)稍微相关的是,您不必自己计算欧几里德距离,有 math.hypot:
slightly related, you don't have to compute the euclidean distance yourself, there's math.hypot:
如果您不介意在两次相同的两点之间进行距离计算,
则以下方法将找到最大距离:为了获得 a 和 b 对,请执行以下操作:
您可以将此与 John Feminella 的解决方案结合起来获得 (a,b) 元组而不进行额外的距离比较
If you don't mind doing distance calculations between two points that are the same twice, the following will find the greatest distance:
In order to have the a and b pair instead, then do the following:
You can combine this with John Feminella's solution to get the (a,b) tuple without doing excess distance comparisons