Question

In: Computer Science

I have defined the class. Rectangle in Python. How do I define a class Canvas with...

I have defined the class. Rectangle in Python. How do I define a class Canvas with the following description:

Class Canvas represents a collection of Rectangles. It has 8 methods. In addition, to the constructor
(i.e. __init__ method) and two methods that override python's object methods (and make your class
user friendly as suggested by the test cases), your class should contain 5 more methods:
add_one_rectangle, count_same_color, total_perimeter, min_enclosing_rectangle, and common_point.

Solutions

Expert Solution

In case of any query do comment. Please rate answer as well. Thanks

Code:

#let's say your class rectangle

class Rectangle():

   

    def __init__(self,length,width,color):

        self.length = length

        self.width = width

        self.color = color

       

    def perimeter(self):

        return 2*(self.length + self.width)

    def __str__(self):

        return "Rectangle with length: {}, width: {}, color: {} and perimeter: {}".format(self.length,self.width,self.color,self.perimeter())

#now define class canvas as asked in the question

class Canvas:

    #method 1 as init   

    def __init__(self,rectangles):

        self.rectangles = rectangles

    #method 2 as __str__

    def __str__(self):

        data =""

        for rectangle in self.rectangles:

            data += str(rectangle) + "\n"

        return data

   

    #method 3 as repr

    def __repr__(self):

        data ="[\n"

        for rectangle in self.rectangles:

            data += "[" + str(rectangle) + "],\n"

        return data + "]"

   

    #given method as add_one_rectangle

    def add_one_rectangle(self,rectangle):

        self.rectangles.append(rectangle)

   

    #given method as count_same_color

    def count_same_color(self,color):

       return sum(p.color == color for p in self.rectangles)

   

    #given method as total_perimeter

    def total_perimeter(self):

        perimeter =0

        for rect in self.rectangles:

            perimeter += rect.perimeter()

        return perimeter

       

    #there was no functionality mentioned for these method , hence pass is used

    def min_enclosing_rectangle(self):

         pass

   

    def common_point(self):

        pass

   

#main driver method

#create a list of rectangles

rectangles=[]

rect1 = Rectangle(5,10,"Red")

rect2 = Rectangle(15,20,"Green")

rect3 = Rectangle(25,30, "Yellow")

rectangles.append(rect1)

rectangles.append(rect2)

rectangles.append(rect3)

#create an object of Canvas class

canvas = Canvas(rectangles)

#print all the methods one by one of canvas class

print(canvas)

print(repr(canvas))

print("Now add one more rectangle")

rect4 = Rectangle(15,40,"Red")

canvas.add_one_rectangle(rect4)

print(canvas)

print("Find matching with Red color: ".format(canvas.count_same_color("Red")))

print("Total Perimeter of all rectangles in Canvas: {}".format(canvas.total_perimeter()))

==========screen shot of the code indentation=======

Output:


Related Solutions

This is python #Create a class called Rectangle. Rectangle should #have two attributes (instance variables): length...
This is python #Create a class called Rectangle. Rectangle should #have two attributes (instance variables): length and #width. Make sure the variable names match those words. #Both will be floats. # #Rectangle should have a constructor with two required #parameters, one for each of those attributes (length and #width, in that order). # #Rectangle should also have a method called #find_perimeter. find_perimeter should calculate the #perimeter of the rectangle based on the current values for #length and width. # #perimeter...
DO THIS IN C#,Design and implement class Rectangle to represent a rectangle object. The class defines...
DO THIS IN C#,Design and implement class Rectangle to represent a rectangle object. The class defines the following attributes (variables) and methods: 1. Two Class variables of type double named height and width to represent the height and width of the rectangle. Set their default values to 1.0 in the default constructor. 2. A non-argument constructor method to create a default rectangle. 3. Another constructor method to create a rectangle with user-specified height and width. 4. Method getArea() that returns...
Using Python Define a Student class. A Student class needs to have two attributes, the student_name...
Using Python Define a Student class. A Student class needs to have two attributes, the student_name and strudent_grade . It also has three methods as follows: set_grade(grade) that sets the grade of the student. get_grade returns the grade of the student. print_student_info that print the name and grade of student in a formatted string. In the math_utils.py file define a function called average_grade(roster) . This method accepts as input a list of Student Objects and returns the average of the...
How do I write a script for this in python in REPL or atom, NOT python...
How do I write a script for this in python in REPL or atom, NOT python shell Consider the following simple “community” in Python . . . triangle = [ ["top", [0, 1]], ["bottom-left", [0, 0]], ["bottom-right", [2, 0]], ] This is the calling of function. >>> nearestneighbor([0, 0.6], triangle, myeuclidean) 'top' The new point is (0, 0.6) and the distance function is Euclidean. Now let’s confirm this result . . . >>> myeuclidean([0, 0.6], [0, 1]) 0.4 >>> myeuclidean([0,...
hi i do not know what is wrong with my python code. this is the class:...
hi i do not know what is wrong with my python code. this is the class: class Cuboid: def __init__(self, width, length, height, colour): self.__width = width self.__length = length self.__height = height self.__colour = colour self.surface_area = (2 * (width * length) + 2 * (width * height) + 2 * (length * height)) self.volume = height * length * width def get_width(self): return self.__width def get_length(self): return self.__length def get_height(self): return self.__height def get_colour(self): return self.__colour def set_width(self,...
In python- Create a class defined for Regression. Class attributes are data points for x, y,...
In python- Create a class defined for Regression. Class attributes are data points for x, y, the slope and the intercept for the regression line. Define an instance method to find the regression line parameters (slope and intercept). Plot all data points on the graph. Plot the regression line on the same plot.
The Pool class of the multiprocessing Python module. There is a defined run method to perform...
The Pool class of the multiprocessing Python module. There is a defined run method to perform the tasks. Create a pool object of the Pool class of a specific number of CPUs your system has by passing a number of tasks you have. Start each task within the pool object by calling the map instance method, and pass the run function and the list of tasks as an argument.Hint: os.walk() generates the file names in a directory tree by walking...
Declare and define a class for a fraction number. A fraction in mathematics is defined as...
Declare and define a class for a fraction number. A fraction in mathematics is defined as a/b, where a and b are integers and called numerator and denominator. Requirements Task1    Define a fraction class that has the following member functions: constructor that initializes the fraction by default arguments. set function that sets the numerator of the fraction. set function that sets the denominator of the fraction. get function that returns the numerator of the fraction. get function that returns...
I have a JavaFx game that you have a rectangle and you move it with the...
I have a JavaFx game that you have a rectangle and you move it with the arrow keys to shoot circles that I call enemies. I want to add some collision to the rectangle so that when it hits the circles the game ends and I also want to add a counter so that each time I shoot an enemy it adds 2 points and when you die it prints out how many points you get. import javafx.animation.AnimationTimer; import javafx.application.Application;...
I have to create a program that: define class cust(I already did this part) create an...
I have to create a program that: define class cust(I already did this part) create an array of cust (size 10)to hold the data of the class. (done) read the date from a file(everything from the class - already done) call a function print cust(this function will print all the data in table format)....first, last, state, sales history(0,1,2), units Read the data from a file (you may break up the strings and numeric values any way you choose (separate lines...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT