9

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!

albert
  • 8,285
  • 3
  • 19
  • 32
Benjamin Brooks
  • 195
  • 3
  • 6
  • 14
  • Try using a for loop for your last line. I am assuming this is an assignment, otherwise you could use `numpy.dot`. – Akavall Sep 19 '15 at 15:21
  • 1
    this seems like homework. Have a look at the `zip` function. – Azsgy Sep 19 '15 at 15:26
  • A more Pythonic function would return `None` on a length mismatch, but hey, I guess you've got to write what your teacher wants. :) – PM 2Ring Sep 19 '15 at 15:34
  • You were told that you *should assume that the input lists contain only numeric values.* So where are you comparing `L` to the empty string? – David Hammen Sep 19 '15 at 16:00

5 Answers5

24

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.

VHarisop
  • 2,816
  • 1
  • 14
  • 28
  • 1
    @BenjaminBrooks: FWIW, VHarisop's code could be condensed to `return sum(i*j for i,j in zip(K, L)) if len(K) == len(L) else 0`, but that might be a bit too fancy for your teacher. :) – PM 2Ring Sep 19 '15 at 15:42
  • 5
    @PM2Ring, I wonder what the teacher would think of `return len(K) == len(L) and sum(starmap(mul, zip(K, L))) or 0` – Padraic Cunningham Sep 19 '15 at 15:52
  • 1
    @PadraicCunningham: Good call. I wonder if the teacher even knows that itertools exists... :) – PM 2Ring Sep 19 '15 at 15:54
  • Wanted to add: if the lengths are not equal you likely want to `raise` an error as the dot product of two vectors of different dimensions is not defined – shayaan Oct 08 '18 at 06:59
11

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

 sum([x*y for x,y in zip(V1,V2)])
abhikarma1493
  • 131
  • 1
  • 6
1

The for loop returns an array that has each K*L element multiplied. Then the sum function adds each element and returns the dot product

def dot(K,L):
    if len(K)==len(L) and len(K)!=0:
        return sum([K[n]*L[n] for n in range(len(K))])
    else:
        return 0
Clayton J Roberts
  • 347
  • 1
  • 5
  • 19
  • Please explain why this resolved the issue. It doesn't help very much if you just post the answer and no explanation. – Serguei Fedorov Jan 19 '16 at 21:46
  • Last line should be `return 0`. Not a terribly valuable answer, given the earlier one, except insofar as it illuminates the algorithm a little more clearly for those too new to recognize `zip`. – Tom Zych Jan 19 '16 at 22:07
1

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
VDV
  • 874
  • 9
  • 12
0
    vector_a = [1., 2., 3.]
    vector_b = [2., 2., 2.]
    z=list(zip(vector_a,vector_b))
    a=sum([x*y for x,y in zip(vector_a,vector_b)])
      for m,n in z:
        print(str(m)+"*",str(n))
    print(a)

    #hope you got it `

Using Zip function provides lesser complexity making it more efficient to use in case of dot products or any multiple list operations.

  • 3
    Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please [edit] your question and explain how it works better than what the OP provided. – ChrisGPT was on strike Apr 22 '20 at 18:48