1

I am trying to find the closest distance between two rectangles (or polygons).

I have the following code:

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

This code works, but it is not pretty, and it is taking too long to run. Any optimization suggestions?

1 Answers1

0

You are making it yourself very complicated by first putting your points into a dictionary and getting them out afterwards. You can probably simplify this to something like this (untested):

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

This creates a generator expression from the output of itertools.product, which you can feed directly to min.

Community
  • 1
  • 1
Bas Swinckels
  • 18,095
  • 3
  • 45
  • 62