0
0
NumPydata~20 mins

np.broadcast_to() for explicit broadcasting in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Broadcasting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A
[[1 1 1]
 [2 2 2]
 [3 3 3]]
B
[[1 2 3]
 [2 3 1]
 [3 1 2]]
C
[[1 2 3]
 [1 2 3]
 [1 2 3]]
D[[1 2 3 1 2 3 1 2 3]]
Attempts:
2 left
💡 Hint
Broadcasting repeats the original array along new dimensions without copying data.
data_output
intermediate
1: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)
A(1, 1)
B(4,)
C(5, 4)
D(4, 5)
Attempts:
2 left
💡 Hint
Broadcasting a scalar repeats it to fill the target shape.
🔧 Debug
advanced
2: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))
AValueError: shape mismatch: objects cannot be broadcast to a single shape
BTypeError: unsupported operand type(s)
CIndexError: index out of bounds
DNo error, output is [[1 2] [3 1]]
Attempts:
2 left
💡 Hint
Broadcasting requires the original shape to be compatible with the target shape.
🚀 Application
advanced
2: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])
Amatrix + np.broadcast_to(bias, (3, 4))
Bmatrix + np.broadcast_to(bias, (4, 3))
Cmatrix + np.broadcast_to(bias, (3,))
Dmatrix + np.broadcast_to(bias, (1, 4))
Attempts:
2 left
💡 Hint
The bias must be broadcast to match the matrix shape exactly.
🧠 Conceptual
expert
2:00remaining
Memory behavior of np.broadcast_to()
Which statement about np.broadcast_to() is TRUE regarding memory usage?
Anp.broadcast_to() creates a new array with copied data to match the target shape.
Bnp.broadcast_to() returns a view that shares the original data without copying.
Cnp.broadcast_to() always returns a deep copy of the original array.
Dnp.broadcast_to() modifies the original array in-place to match the new shape.
Attempts:
2 left
💡 Hint
Broadcasting tries to avoid copying data for efficiency.