How to calculate the center of a rectangle in Python

1 Answer

0 votes
class Point:
    def __init__(self, x: float, y: float):
        self.x = x
        self.y = y

class Rectangle:
    def __init__(self, top_left: Point, bottom_right: Point):
        self.top_left = top_left
        self.bottom_right = bottom_right

def get_center(rect: Rectangle) -> Point:
    center_x = (rect.top_left.x + rect.bottom_right.x) / 2.0
    center_y = (rect.top_left.y + rect.bottom_right.y) / 2.0
    return Point(center_x, center_y)


rect = Rectangle(Point(10.0, 20.0), Point(110.0, 70.0))
center = get_center(rect)

print(f"Center of the rectangle: ({center.x:.2f}, {center.y:.2f})")



'''
run:

Center of the rectangle: (60.00, 45.00)

'''

 



answered Jun 22, 2025 by avibootz

Related questions

1 answer 100 views
1 answer 73 views
1 answer 89 views
2 answers 122 views
...