4

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)
Alligator
  • 691
  • 3
  • 11
  • 21
  • *"I'd like to be able to find a row"* - sorry, I don't get it. What does it mean, to find a row? You already know the coordinates, don't you? – Pavel May 29 '14 at 18:40
  • I simply meant to identify a row for further processing. For example, I may want to find a point on the nth row up from the origin. – Alligator May 29 '14 at 19:14

4 Answers4

6

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.

whereswalden
  • 4,819
  • 3
  • 27
  • 41
1

depending on what you want to do with the coordinates, you can also misuse the complex numbers:

import cmath

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

print New_Row_End_Coordinate.real
print New_Row_End_Coordinate.imag
Pavel
  • 7,436
  • 2
  • 29
  • 42
0

Python doesn't natively support elementwise operations on lists; you could do it via list comprehensions or map but that's a little clunky for this use case. If you're doing a lot of this kind of thing, I'd suggest looking at NumPy.

tzaman
  • 46,925
  • 11
  • 90
  • 115
0

For a = (0,2) and b = (0,0) a + b will yield (0, 2, 0, 0), which is probably not what you want. I suggest to use numpy's add function: http://docs.scipy.org/doc/numpy/reference/generated/numpy.add.html

Parameters : x1, x2 : array_like

Returns: The sum of x1 and x2, element-wise. (...)

Community
  • 1
  • 1
timgeb
  • 76,762
  • 20
  • 123
  • 145