What is the pythonic way to calculate dot product?

Question:

I have two lists, one is named as A, another is named as B. Each element in A is a triple, and each element in B is just an number. I would like to calculate the result defined as :

result = A[0][0] * B[0] + A[1][0] * B[1] + ... + A[n-1][0] * B[n-1]

I know the logic is easy but how to write in pythonic way?

Thanks!

Asked By: xiao 啸

||

Answers:

Probably the most Pythonic way for this kind of thing is to use numpy. 😉

Answered By: Keith
import numpy
result = numpy.dot( numpy.array(A)[:,0], B)

http://docs.scipy.org/doc/numpy/reference/

If you want to do it without numpy, try

sum( [a[i][0]*b[i] for i in range(len(b))] )
Answered By: user57368

My favorite Pythonic dot product is:

sum([i*j for (i, j) in zip(list1, list2)])

So for your case we could do:

sum([i*j for (i, j) in zip([K[0] for K in A], B)])
Answered By: greggomann

Using the operator and the itertools modules:

from operator import mul
from itertools import imap

sum(imap(mul, A, B))
Answered By: NachoGomez
from operator import mul

sum(map(mul, A, B))
Answered By: Dmitry Zotikov

This might be repeated solution, however:

>>> u = [(1, 2, 3), (4, 5, 6)]
>>> v = [3, 7]

In plain Python:

>>> sum([x*y for (x, *x2), y in zip(u,v)])
31

Or using numpy (as described in user57368‘s answer) :

import numpy as np
>>> np.dot(np.array(u)[:,0], v)
31
Answered By: Aziz Alto

Python 3.5 has an explicit operator @ for the dot product,
so you can write

a = A @ B

instead of

a = numpy.dot(A,B)
Answered By: Henri Andre

All above answers are correct, but in my opinion the most pythonic way to calculate dot product is:

>>> a=[1,2,3]
>>> b=[4,5,6]
>>> sum(map(lambda pair:pair[0]*pair[1],zip(a,b)))
32
Answered By: valenta
>>> X = [2,3,5,7,11]
>>> Y = [13,17,19,23,29]
>>> dot = lambda X, Y: sum(map(lambda x, y: x * y, X, Y))
>>> dot(X, Y)
652

And that’s it.

Answered By: qezt

Using more_itertools, a third-party library that implements the dotproduct itertools recipe:

import more_itertools as mit


a = [1, 2, 3]
b = [7, 8, 9]

mit.dotproduct(a, b)
# 50
Answered By: pylang

People are re-assigning the @ operator as the dot product operator. Here’s my code using vanilla python’s zip which returns a tuple. Then uses list comprehension instead of map.

def dot_product(a_vector,b_vector):
    #a1 x b1 + a2 * b2..an*bn return scalar
    return sum([an*bn for an,bn in zip(a_vector,b_vector)])

X = [2,3,5,7,11]
Y = [13,17,19,23,29]
print(dot_product(X,Y)) #652

a=[1,2,3]
b=[4,5,6]
print(dot_product(a,b)) #prints 32= 1*4 + 2*5 + 3*6 = 
a = [1, 2, 3]
b = [7, 8, 9]
print(dot_product(a,b)) #prints 50 
Answered By: Omar Khan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.