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*K, L*K, ect.)
Can someone help me please because I can't figure out what to do in the last line!
You can do this using a list comprehension:
def dot(K, L): if len(K) != len(L): return 0 return sum(i * i 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.