views:

48

answers:

2

How to implement vector sum, using functional programming in python.
This code work for n <100, but not for n > 1000.

from itertools import *

#n=10000 # do not try!!!
n=100
twin=((i,i**2,i**3) for i in xrange(1,n+1))

def sum(x=0,y=0):
    return x+y

def dubsum(x,y):
    return (reduce(sum,i) for i in izip(x,y) )

print [ i for i in reduce(dubsum,twin) ]
+2  A: 

Like this:

print [sum(e) for e in izip(*twin)]

Or even more functionally:

print map(sum, izip(*twin))

Note that zipping is very much like transposing a two-dimensional array.

>>> zip([1, 2, 3, 4],
...     [5, 6, 7, 8])  ==  [(1, 5),
...                         (2, 6),
...                         (3, 7),
...                         (4, 8)]
True
Jason Orendorff
what does *twin stands for?
ralu
`*twin` unpacks the elements of `twin` before passing them to a function. If `twin` is `((1,1,1),(2,4,8))` then `izip(twin)` would be `izip(((1,1,1),(2,4,8)))`, but `izip(*twin)` would be `izip((1,1,1),(2,4,8))`. Check the tutorial in the documentation under "unpacking argument lists".
Peter Milley
A: 

Python has built in sum, why bother:

from itertools import *

n=10000
twin=((i,i**2,i**3) for i in xrange(1,n+1))
x,y,z= izip(*twin)

print sum(x),sum(y),sum(z)
Tony Veijalainen