14

Does this Python code actually find the dot product of two vectors?

import operator

vector1 = (2,3,5)
vector2 = (3,4,6)
dotProduct = reduce( operator.add, map( operator.mul, vector1, vector2))
BSasuke
  • 79
  • 1
  • 1
  • 7
user458858
  • 455
  • 3
  • 6
  • 17

2 Answers2

48

Yes it does. Here is another way

>>> sum(map( operator.mul, vector1, vector2))
48

and another that doesn't use operator at all

>>> vector1 = (2,3,5)
>>> vector2 = (3,4,6)
>>> sum(p*q for p,q in zip(vector1, vector2))
48
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • 1
    nice, the only thing is that you missed the [] of the list comprehension. – chuse Jul 19 '12 at 12:08
  • 13
    @chuse, there is no list comprehension, it's a generator expression – John La Rooy Jul 19 '12 at 12:54
  • 4
    wow, I didn't knew that this existed. In fact, I always used stuff like `sum(map(lambda x:f(x), list))`, then I went to `sum([ f(x) for x in list])`, now I can do `sum(f(x) for x in list)`. Cool. – chuse Jul 23 '12 at 15:16
7

You can also use the numpy implementation of dot product which has large array optimizations in native code to make computations slightly faster. Even better unless you are specifically trying to write a dot product routine or avoid dependencies, using a tried tested widely used library is much better than rolling your own.

whatnick
  • 5,400
  • 3
  • 19
  • 35