Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dot Product in Python without NumPy

Is there a way that you can preform a dot product of two lists that contain values without using NumPy or the Operation module in Python? So that the code is as simple as it could get?

For example:

V_1=[1,2,3]
V_2=[4,5,6]

Dot(V_1,V_2)

Answer: 32

like image 974
Michael Minkoff Avatar asked Feb 04 '16 17:02

Michael Minkoff


2 Answers

Without numpy, you can write yourself a function for the dot product which uses zip and sum.

>>> def dot(v1, v2):
...     return sum(x*y for x, y in zip(v1, v2))
... 
>>> dot([1, 2, 3], [4, 5, 6])
32

As of Python 3.10, you can use zip(v1, v2, strict=True) to ensure that v1 and v2 have the same length.

like image 198
timgeb Avatar answered Sep 22 '22 23:09

timgeb


def dot_product(x, y):
    dp = 0
    for i in range(len(x)):
        dp += (x[i]*y[i])
    return dp

sample1 = [1,2,3,4,5]
sample2 = [2,1,1,1,1]

dot_product(sample1, sample2) #16
like image 21
Plotslut Avatar answered Sep 21 '22 23:09

Plotslut