开发者

dot product in python [closed]

开发者_如何学Python It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 9 years ago.

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))


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜