19、标题:矩形相交的面积
【矩形相交的面积】在坐标系中,给定3个矩形,求相交区域的面积。
输入描述:
3行输入分别为3个矩形的位置,分别代表“左上角x坐标”,“左上角y坐标”,“矩形宽”,“矩形高” -1000<=x,y<1000
输出描述:
输出3个矩形相交的面积,不相交的输出0
示例:
输入
1 6 4 4
3 5 3 4
0 3 7 3
输出
2
def square_intersection_area(s1, s2, s3):
a1 = [int(x) for x in s1.split(" ")]
a2 = [int(x) for x in s2.split(" ")]
a3 = [int(x) for x in s3.split(" ")]
def have_comm(aaa1, aaa2):
"""返回两个区间的交集"""
if aaa1[0] <= aaa2[0] and aaa1[1] >= aaa2[0]:
return [aaa2[0], min(aaa1[1], aaa2[1])]
elif aaa2[0] <= aaa1[0] and aaa2[1] >= aaa1[0]:
return [aaa1[0], min(aaa1[1], aaa2[1])]
return False
def area(aa1, aa2):
"""返回相交部分矩形的信息数组:[“左上角x坐标”,“左上角y坐标”,“矩形宽”,“矩形高”]"""
a = [aa1[0], aa1[0] + aa1[2]] # 矩形1的x坐标区间
b = [aa2[0], aa2[0] + aa2[2]] # 矩形2的x坐标区间
c = [aa1[1] - aa1[3], aa1[1]] # 矩形1的y坐标区间
d = [aa2[1] - aa2[3], aa2[1]] # 矩形2的y坐标区间
# 当区间a、b有交集,且区间d、d有交集的时候,说明矩形1、2相交
if have_comm(a, b) and have_comm(c, d):
xx = have_comm(a, b)
yy = have_comm(c, d)
return [xx[0], yy[1], xx[1] - xx[0], yy[1] - yy[0]]
return False
area1 = area(a1, a2)
area2 = area(area1, a3) if area1 else False
if area2:
return area2[2] * area2[3]
return 0
print(square_intersection_area("1 6 4 4", "3 5 3 4", "0 3 7 3"))