【问题标题】:Find the two closest corner points between two rectangles (in python)找到两个矩形之间最近的两个角点(在python中)
【发布时间】:2014-08-12 18:50:44
【问题描述】:

我试图找到两个矩形(或多边形)之间的最近距离。

我有以下代码:

def hypotenuse(point1,point2):
    '''
    gives you the length of a line between two
    points
    '''
    x1, y1, z1 = point1
    x2, y2, z2 = point2

    x_distance = abs(x2 - x1)
    y_distance = abs(y2 - y1)

    hypotenuse_length = ((x_distance**2) + (y_distance**2))**.5

    return hypotenuse_length



def shortest_distance_between_point_lists(lst_a, lst_b):
    '''
    Tells you the shortest distance (clearance) between two
    sets of points. Assumes objects are not overlapping.
    '''

    lst_dicts =([dict(zip(('lst_a','lst_b'), (i,j))) for i,j\
    in itertools.product(lst_a,lst_b)])

    shortest_hypotenuse = 1000000000

    for a_dict in lst_dicts:
        point1 =  a_dict.get('lst_a')
        point2 = a_dict.get('lst_b')
        current_hypotenuse = hypotenuse(point1,point2)
        if (current_hypotenuse < shortest_hypotenuse):
            shortest_hypotenuse = current_hypotenuse
            shortest_dict = a_dict

    return shortest_hypotenuse

这段代码可以运行,但它并不漂亮,而且运行时间太长。有什么优化建议吗?

【问题讨论】:

  • 代码优化/审查问题可以在codereview.stackexchange.com提出
  • 一方面,x2-x1 和 y2-y1 周围的 abs() 不是必需的,但这是一件非常小的事情。

标签: python optimization polygon distance point


【解决方案1】:

首先将您的观点放入字典中,然后再将它们取出来,这让您自己变得非常复杂。您可能可以将其简化为如下所示(未经测试):

shortest = min(hypotenuse(p1, p2) for p1, p2 in itertools.product(lst_a, lst_b))

这会根据itertools.product 的输出创建一个generator expression,您可以将其直接提供给min

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-03
    • 2012-08-18
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    相关资源
    最近更新 更多