Dot product of two lists in Python
Dot product of two lists in Python
You can do this using a list comprehension:
def dot(K, L):
if len(K) != len(L):
return 0
return sum(i[0] * i[1] for i in zip(K, L))
If either of the lists is empty, zip(K, L)
will return []
. Then, by definition, sum([])
will give you zero.
Using list comprehension, given V1 and V2 are two vectors(lists):
sum([x*y for x,y in zip(V1,V2)])
Dot product of two lists in Python
One liner which works for vectors of voluntary size (you may want to define it as a more regular and readable function or change the code to use sum
instead of leftmost reduce
). It does not define multiplication for non-equal lengths as it is not a part of standard dot product definition –it will just report an error on non-equal lengths:
dotprod =lambda K, L:reduce(lambda z1, z2: z1+z2, map(lambda x: reduce(lambda x1, x2: x1*x2, x), zip(K, L)))
Quick test:
dotprod([1, 2, 3, 4], [5, 6, 7, 8])
Out[39]: 70
5+12+21+32
Out[40]: 70
if you still wish to incorporate the length checks and definition for non-equals multiplication:
dotprod =lambda K, L: reduce(lambda z1, z2: z1+z2, map(lambda x: reduce(lambda x1, x2: x1*x2, x), zip(K, L))) if len(K)==len(L) else 0
dotprod([1, 2, 3, 4], [5, 6, 7, 8])
Out[43]: 70
dotprod([1, 2, 3, 4], [5, 6, 7])
Out[44]: 0