what do people use for 2D coordinates?
John Hunter
jdhunter at ace.bsd.uchicago.edu
Sun Aug 3 14:41:41 EDT 2003
>>>>> "Andy" == Andy C <aayycc88 at hotmail.com> writes:
Andy> You could use tuples or complex numbers (seems like a bit of
Andy> a hack). I saw somewhere it said that tuples are useful for
Andy> coordinates. But I haven't found a nice way to add
Andy> coordinates, since + does concatenation on tuples.
If performance is not a major issue, and you want to be able to
generalize to arbitrary dimension, it is rather easy to write a python
class to do the work for you, implementing the special methods
__add__, __iadd__, __sub__ etc
class Coord:
def __init__(self, tup):
self.tup = tup
def __add__(self, other):
if len(other.tup) != len(self.tup): raise ValueError
return Coord( [ x+y for x,y in zip(self.tup, other.tup)] )
def __sub__(self, other):
if len(other.tup) != len(self.tup): raise ValueError
return Coord( [ x-y for x,y in zip(self.tup, other.tup)] )
def __repr__(self):
return str(self.tup)
def __len__(self):
return len(self.tup)
x = Coord( (1,2) )
y = Coord( (2,3) )
print x+y
print x-y
x = Coord( (1,2,4,5) )
y = Coord( (2,3,6,7) )
print x+y
print x-y
Of course, the Numeric module does element-wise array math by default,
do you might want to implement this in numeric if performance is an
issue.
John Hunter
More information about the Python-list
mailing list