Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dot product of two lists in Python

I need to write the function dot( L, K ) that should output the dot product of the lists L and K. If these two input lists are not of equal length, dot should output 0. If these two lists are both empty, dot also should output 0. You should assume that the input lists contain only numeric values.

This is what I have so far:

def dot( L, K ):
    if len[L]!=len[K]:
        return 0
    elif L == '' or L == []:
        return 0
    else:
        return sum(L[0]*K[0], L[1]*K[1], ect.)

Can someone help me please because I can't figure out what to do in the last line!

like image 772
Benjamin Brooks Avatar asked Sep 19 '15 15:09

Benjamin Brooks


3 Answers

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.

like image 111
VHarisop Avatar answered Sep 23 '22 22:09

VHarisop


Using list comprehension, given V1 and V2 are two vectors(lists):

 sum([x*y for x,y in zip(V1,V2)])
like image 34
abhikarma1493 Avatar answered Sep 23 '22 22:09

abhikarma1493


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
like image 25
VDV Avatar answered Sep 21 '22 22:09

VDV