How can I manipulate cartesian coordinates in Python?

Alligator picture Alligator · May 29, 2014 · Viewed 8.2k times · Source

I have a collection of basic cartesian coordinates and I'd like to manipulate them with Python. For example, I have the following box (with coordinates show as the corners):

0,4---4,4

0,0---4,0

I'd like to be able to find a row that starts with (0,2) and goes to (4,2). Do I need to break up each coordinate into separate X and Y values and then use basic math, or is there a way to process coordinates as an (x,y) pair? For example, I'd like to say:

New_Row_Start_Coordinate = (0,2) + (0,0)
New_Row_End_Coordinate = New_Row_Start_Coordinate + (0,4)

Answer

whereswalden picture whereswalden · May 29, 2014

Sounds like you're looking for a Point class. Here's a simple one:

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

  def __str__(self):
    return "{}, {}".format(self.x, self.y)

  def __neg__(self):
    return Point(-self.x, -self.y)

  def __add__(self, point):
    return Point(self.x+point.x, self.y+point.y)

  def __sub__(self, point):
    return self + -point

You can then do things like this:

>>> p1 = Point(1,1)
>>> p2 = Point(3,4)
>>> print p1 + p2
4, 5

You can add as many other operations as you need. For a list of all of the methods you can implement, see the Python docs.