Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Python

Idiom #179 Get center of a rectangle

Return the center c of the rectangle with coördinates(x1,y1,x2,y2)

center = ((x1+x2)/2, (y1+y2)/2)

center is a tuple that can be accessed using index 0 for x and 1 for y.

e.g. center[0]
class Rectangle:
    def __init__(self, x, y, w, h):
        self.x, self.y = x, y
        self.w, self.h = w, h
    def center(self):
        return {
            'x': (self.x + self.w) / 2,
            'y': (self.y + self.h) / 2
        }
w, h = x2 - x1, y2 - y1
r = Rectangle(x1, y1, w, h)
c = r.center()
from collections import namedtuple
Point = namedtuple('Point', 'x y')
center = Point((x1+x2)/2, (y1+y2)/2)

center is a namedtuple, that can be accessed either using x and y or an index (0,1)

e.g. center.x or center[0]
(defn c 
  "calculates the center c of a rectangle of coordinates(x1, y1, x2, y2)" 
  [x1 y1 x2 y2]
  {:x (/ (+ x1 x2) 2)
   :y (/ (+ y1 y2) 2)})

New implementation...
< >
Bart