import sys
def perimeter(rectangles):
perimeter = 0
edges = {}
for rect in rectangles:
x1, y1, x2, y2 = map(int, rect.split())
perimeter += 2 * (x2 - x1 + y2 - y1)
for x, y in [(x1, y1), (x2, y2)]:
if (x, y) in edges:
edges[(x, y)] += 1
if edges[(x, y)] == 2:
perimeter -= 2
else:
edges[(x, y)] = 1
for x in range(x1+1, x2):
for y, side in ((y1, -1), (y2, 1)):
if (x, y) in edges:
edges[(x, y)] += side
if edges[(x, y)] == 2:
perimeter -= 2
else:
edges[(x, y)] = side
for y in range(y1+1, y2):
for x, side in ((x1, -1), (x2, 1)):
if (x, y) in edges:
edges[(x, y)] += side
if edges[(x, y)] == 2:
perimeter -= 2
else:
edges[(x, y)] = side
return perimeter
if __name__ == '__main__':
if len(sys.argv) != 2:
print(f"Usage: python {sys.argv[0]} <input_file>")
sys.exit(1)
input_file = sys.argv[1]
with open(input_file, 'r') as f:
rectangles = [line.strip() for line in f.readlines()]
result = perimeter(rectangles)
print(result)
Save this code in a file (e.g., perimeter.py) and run it with the input file path as an argument:
python perimeter.py input.txt
This code reads the contents of the file input.txt, where each line represents a rectangle in the format x1 y1 x2 y2. It calculates the perimeter of the boundary of all rectangles, including their internal perimeters, and prints the result to the console.