# rectangle.py # Steve Marschner (srm2) and Lillian Lee (ljl2) # March 13, 2013 """Lecture demo: Class to represent 2D rectangles.""" class Rectangle(object): """Instances represent rectangular regions of the plane. Instance variables: l [float]: x coordinate of left edge r [float]: x coordinate of right edge b [float]: y coordinate of bottom edge t [float]: y coordinate of top edge For all Rectangles, l <= r and b <= t. """ def __init__(self, l, r, b, t): """The rectangle [l, r] x [b, t] Pre: args are floats; l <= r; b <= t """ self.l = l self.r = r self.b = b self.t = t def area(self): """Return: area of the rectangle. """ return (self.r - self.l) * (self.t - self.b) def intersection(self, other): """Return: new Rectangle describing intersection of self with other. """ l = max(self.l, other.l) r = min(self.r, other.r) b = max(self.b, other.b) t = min(self.t, other.t) if (r < l): r = l if (t < b): t = b return Rectangle(l, r, b, t) def __str__(self): """String representation of this rectangle.""" return "(%g, %g) x (%g, %g)" % (self.l, self.r, self.b, self.t) if __name__ == '__main__': r1 = Rectangle(0., 1., 2., 3.) print r1.area() r2 = Rectangle(.5, 2., 2.5, 9.) print r2.area() r3 = r1.intersection(r2) r4 = r2.intersection(r1) print r3, r4