Skip to main content

Exercises 13.13 Exercises

1.

Suppose you have a Rectangle object and wish to create a new rectangle that has been scaled by some amount. For example, a 3 by 5 rectangle scaled up by a factor of two would be 6 by 10. A rectangle with width 24 and height 18 scaled by a factor of one-third would have a width of 8 and a height of 6. We would like to write a method called scale that takes a factor as a parameter and returns the scaled Rectangle.
Solution.
class Rectangle:
    """ Rectangle class for representing and manipulating width and height. """

    def __init__(self, init_width, init_height):
        """ Create a new point at the given coordinates. """
        self.width = init_width
        self.height = init_height
          
    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * (self.width + self.height)

    def diagonal_length(self):
        return ((self.width ** 2) + (self.height ** 2)) ** 0.5

    def __str__(self):
        return f"width={self.width}, height={self.height}"

    def scale(self, factor):
         width = self.width * factor
         height = self.height * factor
         return Rectangle(width, height)

r1 = Rectangle(3, 5)
big_r1 = r1.scale(2)
print(big_r1)

r2 = Rectangle(24, 18)
small_r2 = r2.scale(1 / 3)
print(small_r2)

2.

Add a method flip to the Rectangle class. This method will return a new Rectangle with the width and height swapped. Thus, if the original rectangle has width 8 and height 12, the returned rectangle will have width 12 and height 8.

3.

Add a method called change that will take two parameters, call them delta_w and delta_h. The method will cause the width and height to be changed by the given amounts. This method will not return a new Rectangle; it will chanage the attributes of the Rectangle. For example, if a rectangle r has width 8 and height 7, and you call r.change(2.5, -1), the rectangle will then have a width of 10.5 and a height of 6.
Solution.
class Rectangle:
    """ Rectangle class for representing and manipulating width and height. """

    def __init__(self, init_width, init_height):
        """ Create a new point at the given coordinates. """
        self.width = init_width
        self.height = init_height
          
    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * (self.width + self.height)

    def diagonal_length(self):
        return ((self.width ** 2) + (self.height ** 2)) ** 0.5

    def __str__(self):
        return f"width={self.width}, height={self.height}"

    # Your code goes here...
    def change(self, delta_w, delta_h):
        self.width += delta_w
        self.height += delta_h
        
r = Rectangle(8, 7)
r.change(2.5, -1)
print(f"Rectangle r now has {r}.")