1

I wondering how i would enter multiple variables into my function:

def Dot_Product(Vector1,Vector2):
     return sum([x*y for x,y in zip(Vector1,Vector2)])   

print Dot_Product([1,2,1],[1,1,1])

I have looked into *args and **kwargs but I'm not sure how I would implement this so that the list comprehension would also iterate over an unknown number of variables. I'm not sure if its possible so if there are any alternatives, they would be greatly appreciated. I understand how *args and **kwargs work however I'm unsure how to implement a list comprehension that would iterate over an unknown number of variables as in the example given i can only iterate over x,y or x,y,z or n number of lists lists at any one as long as I know what number n is. Since i don't know n how can i change the list comprehension to handle that?

Aaron
  • 155
  • 3
  • 11
  • 1
    possible duplicate of [\*args and \*\*kwargs?](http://stackoverflow.com/questions/3394835/args-and-kwargs) – Tim Aug 31 '15 at 22:11
  • i understand how *args and **kwargs are used not not how to implement them in \ list comprehension so that it iterates over an unknown number of lists – Aaron Aug 31 '15 at 22:17

1 Answers1

3

You can try this approach:

multiplication = lambda x,y: x*y

def dot_product(*args):
    return sum([reduce(multiplication, arg) for arg in zip(*args)])

And then you can pass as many arguments as you want:

In [5]: print dot_product([1,2,1], [1,1,1])
4

In [6]: print dot_product([1,2,1], [1,1,1], [1,1,1])
4

You can check the reduce function here

I think you will also need to validate that all of the items are lists and they have the same length.

Also, as a suggestion by @PauloAlmeida the multiplication variable is not needed as the standard library provides it to us, we can import it like this:

from operator import mul

and then we can use mul instead of multiplication variables which represents the lambda function used on the reduce function.

avenet
  • 2,894
  • 1
  • 19
  • 26
  • Thank you for the helpful answer and the link to the reduce column, it was very helpful. Also thank you for the tips on checking the inputs – Aaron Aug 31 '15 at 22:23
  • Instead of the `lambda` you can also do `from operator import mul`. – Paulo Almeida Aug 31 '15 at 22:33
  • Yes you are right @PauloAlmeida, I thought about it before adding the answer, but I forgot it after...I will add it in the answer. Thank you!! – avenet Aug 31 '15 at 22:36