Dot Product and Matrix Multiplication Practice Problem
This data science coding problem helps you practice Linear Algebra with NumPy, dot product and matrix multiplication, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Linear Algebra with NumPy.
- Problem ID: 65
- Problem key: 65-dot-product-and-matrix-multiplication
- URL: https://datacrack.app/solve/65-dot-product-and-matrix-multiplication
- Difficulty: easy
- Topic: Linear Algebra with NumPy
- Module: NumPy Foundations
Problem Statement
# 🧩 Dot Product and Matrix Multiplication
---
### 🎯 Goal
The dot product and matrix multiplication are the **most fundamental operations in machine learning**. Every linear layer in a neural network is a matrix multiplication. Every prediction in linear regression is a dot product. Without fluency in these, no ML implementation is possible.
---
### 🔍 The Operations
**Dot product** (two 1D vectors):
$$
\mathbf{a} \cdot \mathbf{b} = \sum_{i} a_i b_i = a_1 b_1 + a_2 b_2 + \cdots + a_n b_n
$$
Result: a **scalar**.
**Matrix multiplication** (2D arrays):
$$
C = AB \quad \text{where} \quad C_{ij} = \sum_k A_{ik} B_{kj}
$$
Shape rule: $(m, k) \times (k, n) \rightarrow (m, n)$ — inner dimensions must match.
---
### 💻 Task
Implement `linear_algebra_op(a, b, operation)`.
---
### 📥 Input
- `a`, `b`: lists (1D for dot product, 2D for matrix multiplication)
- `operation`: string — `"dot"` or `"matmul"`
### 📤 Output
- Scalar (for dot product) or nested list (for matrix multiplication)
---
### 🧩 Starter Code
```python
import numpy as np
def linear_algebra_op(a, b, operation):
"""
Perform dot product or matrix multiplication.
Args:
a (list): First array (1D or 2D)
b (list): Second array (1D or 2D)
operation (str): "dot" | "matmul"
Returns:
number or list: Result
"""
arr_a = np.array(a)
arr_b = np.array(b)
if operation == "dot":
# 🧠 TODO: np.dot(arr_a, arr_b) — returns a scalar
pass
elif operation == "matmul":
# 🧠 TODO: arr_a @ arr_b — returns a matrix
pass
```
---
### 🔑 Key Concepts
- `np.dot(a, b)` for 1D: computes the dot product (scalar)
- `A @ B` or `np.matmul(A, B)` for 2D: matrix multiplication
- Shape rule: `(m, k) @ (k, n) → (m, n)` — if inner dims don't match, NumPy raises `ValueError`Starter Code
import numpy as np
def linear_algebra_op(a, b, operation):
"""
Perform dot product or matrix multiplication.
Args:
a (list): First array (1D or 2D)
b (list): Second array (1D or 2D)
operation (str): "dot" | "matmul"
Returns:
number or list: Result
"""
arr_a = np.array(a)
arr_b = np.array(b)
if operation == "dot":
# 🧠 TODO: np.dot(arr_a, arr_b) — returns a scalar
pass
elif operation == "matmul":
# 🧠 TODO: arr_a @ arr_b — returns a matrix
pass