This Python program reads the coordinates of two rectangles from the user.
Each rectangle is defined by two opposite corners (as floating-point pairs).
The program calculates the area of the overlapping region between the two rectangles.
If there is no overlap, the result will be zero.
def intersection_area(r1, r2):
x_overlap = max(0, min(r1['x2'], r2['x2']) - max(r1['x1'], r2['x1']))
y_overlap = max(0, min(r1['y2'], r2['y2']) - max(r1['y1'], r2['y1']))
return x_overlap * y_overlap
# Input for rectangle 1
print("Rectangle 1:")
x1, y1 = map(float, input("First point (x y): ").split())
x2, y2 = map(float, input("Second point (x y): ").split())
r1 = {'x1': min(x1, x2), 'y1': min(y1, y2), 'x2': max(x1, x2), 'y2': max(y1, y2)}
# Input for rectangle 2
print("Rectangle 2:")
x3, y3 = map(float, input("First point (x y): ").split())
x4, y4 = map(float, input("Second point (x y): ").split())
r2 = {'x1': min(x3, x4), 'y1': min(y3, y4), 'x2': max(x3, x4), 'y2': max(y3, y4)}
# Calculate intersection area
area = intersection_area(r1, r2)
print(f"Overlapping area: {area}")
Rectangle 1:
First point (x y): 1 1
Second point (x y): 5 5
Rectangle 2:
First point (x y): 3 3
Second point (x y): 6 6
Overlapping area: 4.0
- Each rectangle is normalized so that x1 < x2 and y1 < y2
- The horizontal and vertical overlap is calculated using min and max
- If the rectangles do not intersect, the overlap dimensions become zero
- The final area is the product of the overlapping width and height