在两个矩形之间找到最接近的两个角点(在Python中)
我正在尝试找出两个矩形(或多边形)之间最近的距离。
我有以下代码:
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
这段代码可以运行,但看起来不太好,而且运行时间太长。有没有什么优化的建议?
1 个回答
0
你把事情搞得太复杂了,先把点放进一个字典里,然后再拿出来。其实你可以把这个过程简化成这样(这个代码没有测试过):
shortest = min(hypotenuse(p1, p2) for p1, p2 in itertools.product(lst_a, lst_b))
这段代码从 itertools.product
的输出中创建了一个 生成器表达式,你可以直接把它传给 min
函数。