Teaching Kids Programming: Videos on Data Structures and Algorithms
Given two vectors of same length, a and b represented by two lists/array in Python, the dot product is defined as follows:
where n is the length of both vectors.
Compute the Dot Product in Python
Traditional loop – going through each index:
1 2 3 4 5 6 7 | def dot(a, b): n = len(a) assert n == len(b) s = 0 for i in range(a): s += a[i] * b[i] return s |
def dot(a, b): n = len(a) assert n == len(b) s = 0 for i in range(a): s += a[i] * b[i] return s
Example: dot([1,2,3],[4,5,6]) = 1*4+2*5+3*6=32
We can implement this using one-liner in Python with help of the zip function:
1 2 3 4 | def dot(a, b): n = len(a) assert n == len(b) return sum(x[0] * x[1] for x in zip(a, b)) |
def dot(a, b): n = len(a) assert n == len(b) return sum(x[0] * x[1] for x in zip(a, b))
The time complexity of dot product computation is O(N) – as we need to go through two arrays in pairs. The space complexity is O(1) constant.
The assert function makes sure the lengths are equal for both vectors – it will stop executing the rest of the code once the condition is not met (check fails)
1 2 3 4 5 6 7 8 | Traceback (most recent call last): File "main.py", line 9, in <module> print(dot([1, 2, 3, 4], [4, 5, 6])) File "main.py", line 6, in dot assert n == len(b) AssertionError </module> |
Traceback (most recent call last): File "main.py", line 9, in <module> print(dot([1, 2, 3, 4], [4, 5, 6])) File "main.py", line 6, in dot assert n == len(b) AssertionError </module>
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
394 wordsloading...
Last Post: Teaching Kids Programming - Prefix Sum Algorithm to Find the Middle Index in Array
Next Post: Teaching Kids Programming - Matrix Add, Subtraction and Multiplication Algorithm