Challenge - 5 Problems
Broadcasting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of np.broadcast_to() with 1D to 2D array
What is the output of this code snippet?
NumPy
import numpy as np arr = np.array([1, 2, 3]) broadcasted = np.broadcast_to(arr, (3, 3)) print(broadcasted)
Attempts:
2 left
💡 Hint
Broadcasting repeats the original array along new dimensions without copying data.
✗ Incorrect
np.broadcast_to repeats the original 1D array along the new axis to match the target shape (3,3). So each row is the original array.
❓ data_output
intermediate1:30remaining
Shape after broadcasting a scalar
What is the shape of the array after broadcasting this scalar to shape (4, 5)?
NumPy
import numpy as np scalar = np.array(7) broadcasted = np.broadcast_to(scalar, (4, 5)) print(broadcasted.shape)
Attempts:
2 left
💡 Hint
Broadcasting a scalar repeats it to fill the target shape.
✗ Incorrect
Broadcasting a scalar to (4,5) creates a 2D array with shape (4,5) filled with the scalar value.
🔧 Debug
advanced2:00remaining
Error when broadcasting incompatible shapes
What error does this code raise?
NumPy
import numpy as np arr = np.array([1, 2, 3]) broadcasted = np.broadcast_to(arr, (2, 2))
Attempts:
2 left
💡 Hint
Broadcasting requires the original shape to be compatible with the target shape.
✗ Incorrect
The original array shape (3,) cannot be broadcast to (2,2) because the last dimension sizes differ and are incompatible.
🚀 Application
advanced2:30remaining
Using np.broadcast_to to add bias to a matrix
Given a 2D array of shape (3, 4) and a 1D bias array of shape (4,), which option correctly broadcasts the bias to add it to each row of the matrix?
NumPy
import numpy as np matrix = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) bias = np.array([10, 20, 30, 40])
Attempts:
2 left
💡 Hint
The bias must be broadcast to match the matrix shape exactly.
✗ Incorrect
Broadcasting bias to (3,4) repeats it for each row, allowing element-wise addition with the matrix.
🧠 Conceptual
expert2:00remaining
Memory behavior of np.broadcast_to()
Which statement about np.broadcast_to() is TRUE regarding memory usage?
Attempts:
2 left
💡 Hint
Broadcasting tries to avoid copying data for efficiency.
✗ Incorrect
np.broadcast_to() returns a read-only view that shares the original data, avoiding memory copies.