How to add using tuples

I have a pseudo code:

if( b < a)
   return (1,0)+foo(a-b,b)

I want to write it in python. But can python add tuples? What is the best way to encode something like this?

+5
source share
4 answers

Do you want to add by elements or add tuples? By default, python does

(1,2)+(3,4) = (1,2,3,4)

You can define your own as:

def myadd(x,y):
     z = []
     for i in range(len(x)):
         z.append(x[i]+y[i])
     return tuple(z)

Also, as @delnan comment explains, it is better written as

def myadd(xs,ys):
     return tuple(x + y for x, y in izip(xs, ys))

or even more functionally:

myadd = lambda xs,ys: tuple(x + y for x, y in izip(xs, ys))

Then do

if( b < a) return myadd((1,0),foo(a-b,b))
+10
source

I will go for

>>> map(sum, zip((1, 2), (3, 4)))
[4, 6]

or, more naturally:

>>> numpy.array((1, 2)) + numpy.array((3, 4))
array([4, 6])
+12
source
tuple(map(operator.add, a, b))

highBandWidth, , Python 2.7 , TypeError. Python 3, map , , a b.

Python 2, map itertools.imap:

tuple(itertools.imap(operator.add, a, b))
+2

, + , tuple :

class mytup(tuple):
    def __add__(self, other):
        if len(self) != len(other):
             return NotImplemented # or raise an error, whatever you prefer
         else:
             return mytup(x+y for x,y in izip(self,other))

__sub__, __mul__, __div__, __gt__ (elementwise >) .. , . ( ) ()

, : tuple.__add__(a,b) a+b. append() , .

+2

All Articles