PDA

View Full Version : Tuple calculations in Python

b1g4L
December 10th, 2007, 11:28 PM
Is there a Python library / function for performing tuple calculations? For instance, I am storing x,y coordinates like...
position = (10,20)

I want to perform tuple addition, so
position = position + 2 assigns position to (12,22).

Currently I have written a function to perform tuple addition, but I would like to eliminate it, if there is a more elegant way of doing this. Any help would be appreciated.

Wybiral
December 10th, 2007, 11:39 PM
It sounds like you want to create your own class and overload the addition operator, here's an example:

class vec2:

def __init__(self, x, y):
self.v = (x, y)

try:
return vec2(self.v[0] + b, self.v[1] + b)
except:
return vec2(self.v[0] + b.v[0], self.v[1] + b.v[1])

def __str__(self):
return "vec2(%f, %f)" % (self.v[0], self.v[1])

a = vec2(10, 20)
b = vec2(30, 40)
print a + b
print a + 2

I should also note that NumPy has all kinds of operations like this!

EDIT:

To save you a Google, http://numpy.scipy.org/

ghostdog74
December 11th, 2007, 12:45 AM
>>> position = (10,20)
>>> [i+2 for i in position]
[12, 22]
>>> tuple([i+2 for i in position])
(12, 22)

b1g4L
December 11th, 2007, 02:23 AM
Thanks for the suggestions. I figured Numeric / NumPy had operations like this, but I've never had a reason to use them. Maybe this is my chance... I also wanted to note that I need the ability to add a tuple to another tuple, not just add a tuple with a constant.

Creating a new class and overloading the + operator is an elegant way to achieve what I want. However, it's not much different than the functions I wrote. The tuples still have to be indexed and added separately. I wonder if it is more or less efficient than functions in Numeric?

pmasiar
December 11th, 2007, 02:52 AM
my bet would be on numpy being more efficient and less buggy than any custom code you could whip in afternoon. And in rare case you will find a bug, fixing it in numpy will fix it for anyone coming to numpy after you.

engla
December 11th, 2007, 03:22 AM
Numpy is more efficient probably; it uses arrays instead of lists and tuples, so it uses much less storage etc. And it's not written in python, much of it is written in C

That said, I couldn't resist.. your new class should be a subclass of tuple of course...

class vec (tuple):
def _binaryop(self, other, op):
try:
return vec(op(a,b) for a,b in zip(self, other))
except:
raise NotImplementedError