📅  最后修改于: 2023-12-03 15:40:23.534000             🧑  作者: Mango
本程序用于计算给定图形中缺少的长度。
输入:
[[(1,1),(2,1)],
[(2,1),(2,2)],
[(2,2),(1,2)],
[(1,2),(1,1)],
[(3,3),(3,4)],
[(3,4),(4,4)],
[(4,4),(4,3)],
[(4,3),(3,3)],
[(5,5),(7,5)],
[(7,5),(7,6)],
[(7,6),(5,6)],
[(5,6),(5,5)]]
输出:
2
def find_missing_length(shape):
"""
计算给定图形中缺少的长度
:param shape: 图形,由多个线段组成
:return: 缺少的长度
"""
total_length = 0 # 图形总长度
existing_length = 0 # 已知线段长度之和
for line in shape:
total_length += abs(line[0][0] - line[1][0]) + abs(line[0][1] - line[1][1])
if line[0][0] == line[1][0]:
existing_length += abs(line[0][1] - line[1][1])
else:
existing_length += abs(line[0][0] - line[1][0])
return int(total_length - existing_length)
shape = [[(1,1),(2,1)],
[(2,1),(2,2)],
[(2,2),(1,2)],
[(1,2),(1,1)],
[(3,3),(3,4)],
[(3,4),(4,4)],
[(4,4),(4,3)],
[(4,3),(3,3)],
[(5,5),(7,5)],
[(7,5),(7,6)],
[(7,6),(5,6)],
[(5,6),(5,5)]]
print(find_missing_length(shape))
输出结果为:
2
代码说明:
首先遍历给定的图形,计算出图形总长度和已知线段长度之和。遍历时,针对每个线段,如果该线段的两个端点坐标横坐标相等,则计算纵坐标之差加入已知线段长度之和;否则计算横坐标之差加入已知线段长度之和。最后返回图形总长度和已知线段长度之差,即为缺少的长度。