Question: Can someone help me with checking rectangle dimensions in python? The purpose of the code is to check two rectangles and are equal if they
Can someone help me with checking rectangle dimensions in python?
The purpose of the code is to check two rectangles and are equal if they have the same number of dimensions, and if for every dimension , the interval of along is equal to the interval of along .
The name of the method I have to write is def rectangle_eq and ### Your CODE HERE is where I have to implement it. Could I get some help? It also has to pass the given tests
import string
class Rectangle(object):
def __init__(self, *intervals, name=None):
"""A rectangle is initialized with a list, whose elements are
either Interval, or a pair of numbers.
It would be perhaps cleaner to accept only list of intervals,
but specifying rectangles via a list of pairs, with each pair
defining an interval, makes for a concise shorthand that will be
useful in tests.
Every rectangle has a name, used to depict it.
If no name is provided, we invent a random one."""
self.intervals = []
for i in intervals:
self.intervals.append(i if type(i) == Interval else Interval(*i))
# I want each rectangle to have a name.
if name is None:
self.name = ''.join(
random.choices(string.ascii_letters + string.digits, k=8))
else:
self.name = name
def __repr__(self):
"""Function used to print a rectangle."""
s = "Rectangle " + self.name + ": "
s += repr([(i.x0, i.x1) for i in self.intervals])
return s
def clone(self, name=None):
"""Returns a clone of itself, with a given name."""
name = name or self.name + "'"
return Rectangle(*self.intervals, name=name)
def __len__(self):
"""Returns the number of dimensions of the rectangle
(not the length of the edges). This is used with
__getitem__ below, to get the interval along a dimension."""
return len(self.intervals)
def __getitem__(self, n):
"""Returns the interval along the n-th dimension"""
return self.intervals[n]
def __setitem__(self, n, i):
"""Sets the interval along the n-th dimension to be i"""
self.intervals[n] = i
@property
def ndims(self):
"""Returns the number of dimensions of the interval."""
return len(self.intervals)
@property
def volume(self):
return np.prod([i.length for i in self.intervals])
############################
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection
matplotlib.rcParams['figure.figsize'] = (6.0, 4.0)
def draw_rectangles(*rectangles, prefix=""):
"""Here, rectangles is a rectangle iterator; it could be a list,
for instance."""
fig, ax = plt.subplots()
patches = []
# We keep track of the limits.
lo_x, hi_x = [], []
lo_y, hi_y = [], []
for r in rectangles:
x0, x1 = r[0].endpoints()
y0, y1 = r[1].endpoints()
lo_x.append(x0)
hi_x.append(x1)
lo_y.append(y0)
hi_y.append(y1)
# Prepares the "patch" for the rectangle, see
# https://matplotlib.org/api/_as_gen/matplotlib.patches.Rectangle.html
p = mpatches.Rectangle((x0, y0), x1 - x0, y1 - y0)
y = (y0 + y1) / 2. - 0.0
x = (x0 + x1) / 2. - 0.0
plt.text(x, y, prefix + r.name, ha="center", family='sans-serif', size=12)
patches.append(p)
# Draws the patches.
colors = np.linspace(0, 1, len(patches) + 1)
collection = PatchCollection(patches, cmap=plt.cm.hsv, alpha=0.3)
collection.set_array(np.array(colors))
ax.add_collection(collection)
# Computes nice ax limits. Note that I need to take care of the case
# in which the rectangle lists are empty.
lox, hix = (min(lo_x), max(hi_x)) if len(lo_x) > 0 else (0., 1.)
loy, hiy = (min(lo_y), max(hi_y)) if len(lo_y) > 0 else (0., 1.)
sx, sy = hix - lox, hiy - loy
lox -= 0.2 * sx
hix += 0.2 * sx
loy -= 0.2 * sy
hiy += 0.2 * sy
ax.set_xlim(lox, hix)
ax.set_ylim(loy, hiy)
plt.gca().set_aspect('equal', adjustable='box')
plt.grid()
plt.show()
############################
def rectangle_eq(self, other):
### YOUR CODE HERE
Rectangle.__eq__ = rectangle_eq
# 5 points: tests for rectangle equality.
assert Rectangle((2, 3), (4, 5)) == Rectangle((2, 3), (4, 5))
assert Rectangle((2, 3), (4, 5)) != Rectangle((4, 5), (2, 3))
assert Rectangle((2, 3), (4, 5)) != Rectangle((2, 3), (4, 5), (6, 7))
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
