Vector Operations
Vector Operations
Implement fundamental vector and matrix operations from scratch. These operations are the building blocks of machine learning.
Functions to implement
1. dot_product(a, b)
Compute the dot product of two vectors.
- Input: Two lists of numbers of equal length
- Output: A single number (the sum of element-wise products)
2. vector_add(a, b)
Add two vectors element-wise.
- Input: Two lists of numbers of equal length
- Output: A list with element-wise sums
3. scalar_multiply(scalar, v)
Multiply a vector by a scalar.
- Input: A scalar and a list of numbers
- Output: A list with each element multiplied by the scalar
4. vector_norm(v)
Compute the L2 (Euclidean) norm of a vector.
- Input: A list of numbers
- Output: The square root of the sum of squared elements
5. matrix_vector_multiply(M, v)
Multiply a matrix by a vector.
- Input: A 2D list (matrix) and a 1D list (vector)
- Output: A list representing the result
Examples
dot_product([1, 2, 3], [4, 5, 6]) # 32
vector_add([1, 2], [3, 4]) # [4, 6]
scalar_multiply(2, [1, 2, 3]) # [2, 4, 6]
vector_norm([3, 4]) # 5.0
matrix_vector_multiply([[1, 2], [3, 4]], [5, 6]) # [17, 39]
Notes
- Do not use NumPy or other libraries
- Implement using only basic Python operations
- You may use
math.sqrtfor the square root
Run tests to see results
No issues detected