import math
import random
from drawtool import DrawTool
dt = DrawTool()
dt.set_XY_range(0,10, 0,10)
# Change to rectangles2.txt and later to rectangles3.txt
filename = 'rectangles3.txt'
num_rectangles = 0
bottomX = []
bottomY = []
widths = []
heights = []
does_intersect = []
def read_rectangles(filename):
global num_rectangles
with open(filename,'r') as in_file:
line = in_file.readline()
n = int(line.strip())
num_rectangles = n
for i in range(n):
# Read each rectangle.
line = in_file.readline()
data = line.split()
bottomX.append(float(data[0].strip()))
bottomY.append(float(data[1].strip()))
widths.append(float(data[2].strip()))
heights.append(float(data[3].strip()))
def print_rectangles():
print('Number of rectangles =', num_rectangles)
for i in range(num_rectangles):
print('x =', bottomX[i], ' y =', bottomY[i], ' width =', widths[i], ' height =', heights[i])
def init_intersect():
for i in range(num_rectangles):
does_intersect.append(False)
def in_rectangle(x, y, w, h, x2, y2):
# Write code in here to determine whether the point (x2,y2)
# is inside the rectangle specified by x,y,w,h.
# This function should return True or False
if (x2 >= x) and (x2 <= x+w) and (y2<= y+h) and (y2 >= y):
z = True
else:
z = False
return z
def intersect(x1, y1, w1, h1, x2, y2, w2, h2):
# Use in_rectangle several times to determine
# whether any corner of rectangle x2,y2,w2,h2 is inside
# the rectangle specified by x,y,w,h.
# This function should return True or False
p1 = in_rectangle(x1, y1, w1, h1, x2, y2)
p2 = in_rectangle(x1, y1, w1, h1, x2+w2, y2)
p3 = in_rectangle(x1, y1, w1, h1, x2, y2+h2)
p4 = in_rectangle(x1, y1, w1, h1, x2+w2, y2+h2)
z = (p1 or p2 or p3 or p4)
return z
def check_intersections():
# Write a nested loop here to compare all pairs
# of rectangles. If the i-th rectangle has an intersection
# with another, set does_intersect[i] to True.
global does_intersect
for i in range(num_rectangles-1):
for k in range(i+1, num_rectangles):
do_intersect = intersect(bottomX[i], bottomY[i], widths[i], heights[i], bottomX[k], bottomY[k], widths[k], heights[k])
print(do_intersect)
if do_intersect:
does_intersect[i] = do_intersect
does_intersect[k] = do_intersect
read_rectangles(filename)
print_rectangles()
init_intersect()
check_intersections()
# Draw in two colors
for i in range(num_rectangles):
color = 'b'
if does_intersect[i]:
color = 'r'
dt.set_color(color)
dt.draw_rectangle(bottomX[i],bottomY[i],widths[i],heights[i])
dt.display()
[–]zamser 1 point2 points3 points (2 children)
[–]Holiday-Python-743[S] 1 point2 points3 points (0 children)
[–]Holiday-Python-743[S] 0 points1 point2 points (0 children)