0
>>> from pandac.PandaModules import Vec3
>>> import numpy
>>> l = []
>>> l.append( Vec3(1,1,1) )
>>> l.append( Vec3(1,1,1) )
>>> l.append( Vec3(1,1,1) )
>>> Vec3(1,1,1)+Vec3(1,1,1)
Vec3(2, 2, 2)
>>> sum(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'libpanda.Vec3'
>>> numpy.sum(l)
9.0
>>> 

i want some fast (fast == not for loop in pure python but numpy velocity) method to achive:

>>> my_smart_sum(l)
Vec3(3,3,3)
nkint
  • 11,513
  • 31
  • 103
  • 174
  • ok i found this method: reduce(lambda x,y:x+y, l) some downside? – nkint Dec 17 '11 at 17:36
  • 1
    There is a downside, and it is most excellently explained [here](http://stackoverflow.com/questions/1892324/why-program-functionally-in-python/1892614#1892614). – Björn Pollex Dec 17 '11 at 18:22

1 Answers1

2

Try this:

sum(l, start=Vec3(0,0,0))

Or, with numpy, this:

numpy.sum(l, axis=0)

The speed depends in the implementation of the vector-addition. You should use timeit to determine which method is fastest. This could look something like this:

python -m timeit "import numpy; foo = [[1,1,1],[1,1,1]]" "numpy.sum(foo, axis=0)"
10000 loops, best of 3: 46.5 usec per loop

The first string you pass is the setup-statement - this will not be included in the timing. The second string you pass is the code you actually want to time. I don't know anything about pandac, but sometimes number-crunching loops can be sped up a lot using Cython.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • sum with start do the trick. because i need a return value of Vec3, and numpy.sum return a numpy array. pandac is a render engine written in c++ and wrapped in python so i think it is ok. – nkint Dec 17 '11 at 17:35
  • any downside on using reduce? – nkint Dec 17 '11 at 17:37