dot products
Nick Coghlan
ncoghlan at iinet.net.au
Sun Dec 19 06:46:03 EST 2004
Rahul wrote:
> HI.
> I want to compute dot product of two vectors stored as lists a and b.a
> and b are of the same length.
>
> one simple way is
> sum(a[i]*b[i] for i in range(len(a)))
>
> another simple way is
> ans=0.0
> for i in range(len(a)):
> ans=ans+a[i]*b[i]
>
> But is there any other way which is faster than any of the above.
Try:
sum(x * y for x, y in zip(a, b))
Between zip() (lockstep iteration over several sequences) and enumerate()
(iteration over a sequence, but also providing an index counter), it is rare
that you will want to use indexing notation in a generator expression.
> (By the way profiling them i found that the second is faster by about 30%.)
For short sequences, generator expressions may end up slightly slower than list
comprehensions or for loops, as the latter two do not involve the overhead of
setting up the generator and retrieving values from it. As the sequences
increase in length, generator expressions generally win in the end due to their
reduced memory impact.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at email.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
More information about the Python-list
mailing list