문제

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))
도움이 되었습니까?

해결책

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.

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top