Python“循环法”

发布于 2024-07-16 08:39:30 字数 549 浏览 6 评论 0原文

给定多个 (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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

人生戏 2024-07-23 08:39:30

在 python 2.6 中,您可以使用 itertools.permutations

import itertools
perms = itertools.permutations(pairs, 2)
distances = (distance(*p) for p in perms)

import itertools
combs = itertools.combinations(pairs, 2)
distances = (distance(*c) for c in combs)

in python 2.6, you can use itertools.permutations

import itertools
perms = itertools.permutations(pairs, 2)
distances = (distance(*p) for p in perms)

or

import itertools
combs = itertools.combinations(pairs, 2)
distances = (distance(*c) for c in combs)
花开浅夏 2024-07-23 08:39:30
try:

    from itertools import combinations

except ImportError:

    def combinations(l, n):
        if n != 2: raise Exception('This placeholder only good for n=2')
        for i in range(len(l)):
            for j in range(i+1, len(l)):
                yield l[i], l[j]


coords_list = [(0,0), (3,4), (6,8)]

def distance(p1, p2):
    return ( ( p2[0]-p1[0] ) ** 2 + ( p2[1]-p1[1] )**2 ) ** 0.5

largest_distance, (p1, p2) = max([
     (distance(p1,p2), (p1, p2)) for (p1,p2) in combinations(coords_list, 2)
     ])


print largest_distance, p1, p2
try:

    from itertools import combinations

except ImportError:

    def combinations(l, n):
        if n != 2: raise Exception('This placeholder only good for n=2')
        for i in range(len(l)):
            for j in range(i+1, len(l)):
                yield l[i], l[j]


coords_list = [(0,0), (3,4), (6,8)]

def distance(p1, p2):
    return ( ( p2[0]-p1[0] ) ** 2 + ( p2[1]-p1[1] )**2 ) ** 0.5

largest_distance, (p1, p2) = max([
     (distance(p1,p2), (p1, p2)) for (p1,p2) in combinations(coords_list, 2)
     ])


print largest_distance, p1, p2
╄→承喏 2024-07-23 08:39:30

尝试:

max(distance(a, b) for (i, a) in enumerate(pairs) for b in pairs[i+1:])

这可以避免身份比较(例如,距离(x,x),距离(y,y)等)。 它还避免了进行对称比较,因为 distance(x, y) == distance(y, x)


更新:我喜欢Evgeny的解决方案 更好地使用 itertools ,因为它更简洁地表达了您想要做的事情。 我们的两种解决方案都做同样的事情。 (注意:确保您使用组合,而不是排列——那样会慢很多!)

Try:

max(distance(a, b) for (i, a) in enumerate(pairs) for b in pairs[i+1:])

This avoid identity-comparisons (e.g. distance(x, x), distance(y, y), etc.). It also avoids doing symmetric comparisons, since distance(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!)

聆听风音 2024-07-23 08:39:30

稍微相关的是,您不必自己计算欧几里德距离,有 math.hypot:

In [1]: a = (1, 2)
In [2]: b = (4, 5)
In [3]: hypot(a[0]-b[0], a[1]-b[1])
Out[3]: 4.2426406871192848

slightly related, you don't have to compute the euclidean distance yourself, there's math.hypot:

In [1]: a = (1, 2)
In [2]: b = (4, 5)
In [3]: hypot(a[0]-b[0], a[1]-b[1])
Out[3]: 4.2426406871192848
掩耳倾听 2024-07-23 08:39:30

如果您不介意在两次相同的两点之间进行距离计算,

max( [distance(a, b) for a in pairs for b in pairs] )

则以下方法将找到最大距离:为了获得 a 和 b 对,请执行以下操作:

import operator
max( [((a,b), distance(a, b)) for a in pairs for b in pairs], key=operator.itemgetter(1))

您可以将此与 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:

max( [distance(a, b) for a in pairs for b in pairs] )

In order to have the a and b pair instead, then do the following:

import operator
max( [((a,b), distance(a, b)) for a in pairs for b in pairs], key=operator.itemgetter(1))

You can combine this with John Feminella's solution to get the (a,b) tuple without doing excess distance comparisons

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文