Dot Product in Python without NumPy
Asked Answered
E

3

9

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

Embrace answered 4/2, 2016 at 17:54 Comment(2)
I just meant using lists that contained values within them.Embrace
I will update the questionEmbrace
M
24

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.

Massif answered 4/2, 2016 at 18:1 Comment(0)
A
1
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
Agape answered 17/12, 2021 at 0:30 Comment(0)
W
0

We can simply use @ operator from python. For example:

import numpy as np
x = np.array([25, 2, 5])
y = np.array([0, 1, 2])

print(x@y)
12
Warison answered 10/3, 2022 at 12:8 Comment(1)
The @ operator is implemented by NumPy; it's not part of native Python.Swick

© 2022 - 2024 — McMap. All rights reserved.