Loading

Quipoin Menu

Learn • Practice • Grow

python-for-ai / NumPy Broadcasting
interview

Q1. You have a 2D array of shape (3,4) representing batch features. You want to subtract the mean of each feature (column) and divide by standard deviation. Write the broadcasting code.
data = np.random.rand(3,4)
mean = data.mean(axis=0)
std = data.std(axis=0)
normalized = (data - mean) / std
Broadcasting aligns (3,4) with (4,) and applies operation to each row. No loops needed.

Q2. Add a constant bias term to each element of a 5x5 matrix. Show two ways: using broadcasting and using np.full.
arr = np.ones((5,5))
bias = 0.5
result1 = arr + bias                    # broadcasting
result2 = arr + np.full((5,5), bias)    # explicit
Both give 1.5 everywhere. Broadcasting automatically expands scalar to array shape.

Q3. Multiply a 3x1 column vector by a 1x4 row vector. What shape is the result? Write code to produce the outer product.
col = np.array([[1],[2],[3]])
row = np.array([[10,20,30,40]])
result = col * row          # shape (3,4)
This is broadcasting: (3,1) * (1,4) → (3,4). Equivalent to np.outer(col.flatten(), row.flatten()).

Q4. You have an array of shape (2,3) and you want to add a 1D array of shape (3,) to each row. Write the code and explain broadcasting rules.
A = np.arange(6).reshape(2,3)
b = np.array([10,20,30])
C = A + b
Shapes: (2,3) and (3,) → (2,3). b is stretched to (2,3) implicitly. This adds b to each row. Works because trailing dimensions match.

Q5. Create a 1D array of 5 numbers. Use broadcasting to compare it with a scalar threshold, producing a boolean array. Then use that boolean array to index the original array.
arr = np.array([2,5,1,8,3])
threshold = 4
mask = arr > threshold   # [False, True, False, True, False]
result = arr[mask]       # [5,8]
Broadcasting scalar to array, then boolean indexing. Useful for thresholding predictions.