← back

Dot Product Calculator

#83 · Linear Algebra · Easy

⊣ Solve on deep-ml.com

Problem

Calculate the dot product of two vectors. The dot product is the sum of element-wise products and is a fundamental operation in linear algebra.

Solution

1
2
3
4
5
6
def dot_product(v1, v2):
    if len(v1) != len(v2):
        raise ValueError("Vectors must have the same length")

    result = sum(a * b for a, b in zip(v1, v2))
    return result

Explanation

  1. Verify both vectors have the same length.
  2. Multiply corresponding elements from each vector.
  3. Sum all the products to get the dot product.
  4. Geometrically, dot(a, b) = ||a|| ||b|| cos(theta), where theta is the angle between them.
  5. A dot product of zero means the vectors are orthogonal (perpendicular).

Complexity

  • Time: O(n) where n is the length of the vectors
  • Space: O(1)