In [16]:
def get_line_intersect(x1, x2):
if x1[0] > x2[0]:
x1, x2 = x2, x1 # make sure x1 is the leftmost line
if x1[1] < x2[0]:
return 0 # there is no intersection
return min(x1[1], x2[1]) - x2[0] # in case one list is fully contained in the other,
# x2[1] will be smaller than x1[1] and will define the intersect length
def get_area_of_love(rect1, rect2):
x = get_line_intersect((rect1['x'], rect1['x']+rect1['width']), (rect2['x'], rect2['x']+rect2['width']))
y = get_line_intersect((rect1['y'], rect1['y']+rect1['height']), (rect2['y'], rect2['y']+rect2['height']))
return x * y
In [21]:
rect1 = {'x': 1, 'y': 5, 'width': 10, 'height': 4}
rect2 = {'x': 20, 'y': 20, 'width': 10, 'height': 10}
rect3 = {'x': 22, 'y': 24, 'width': 4, 'height': 4}
In [22]:
get_area_of_love(rect1, rect1)
Out[22]:
In [23]:
get_area_of_love(rect1, rect2)
Out[23]:
In [24]:
get_area_of_love(rect2, rect3)
Out[24]: