Python – How to find horizontal distance between two rectangles?

The distance from one vertical edge to another is either from the right-hand side of rect1 to the left-hand side of rect2, or the other way around. You don’t need to know which rectangle is the one on the left or right; you can take the smaller of the two possible values.

rect1 = {'x':515, 'y':942, 'w':525, 'h':954}
rect2 = {'x':382, 'y':938, 'w':508, 'h':960}
min(rect1['x']+rect1['w']-rect2['x'],rect2['x']+rect2['w']-rect1['x'])
>>> 375

Even though your rectangles overlap, this still is the correct value:

382    515     890  1040
 +--------------+
 :              :
 :      +------------+
 :      |       :    |
 :      +------------+
 :              :
 +--------------+
        <- 375 ->

Leave a Comment