0
0
NumPydata~20 mins

Why broadcasting matters in NumPy - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Broadcasting Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of adding arrays with broadcasting
What is the output of this code snippet using NumPy broadcasting?
NumPy
import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([[10], [20], [30]])
result = arr1 + arr2
print(result)
AValueError: operands could not be broadcast together with shapes (3,) (3,1)
B
[[11 12 13]
 [21 22 23]
 [31 32 33]]
C
[[10 20 30]
 [11 21 31]
 [12 22 32]]
D
[[11 12 13 10]
 [21 22 23 20]
 [31 32 33 30]]
Attempts:
2 left
💡 Hint
Think about how NumPy aligns shapes when adding arrays of different dimensions.
data_output
intermediate
1:30remaining
Shape of result after broadcasting
Given these arrays, what is the shape of the result after broadcasting and addition?
NumPy
import numpy as np

x = np.ones((4,1))
y = np.arange(3)
z = x + y
A(4, 3)
B(4, 1)
C(3, 4)
D(1, 3)
Attempts:
2 left
💡 Hint
Broadcasting expands dimensions to match the largest shape.
🔧 Debug
advanced
2:00remaining
Identify the broadcasting error
Why does this code raise an error?
NumPy
import numpy as np

arr1 = np.array([1, 2])
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
result = arr1 + arr2
AIndexError: index out of bounds
BTypeError: unsupported operand type(s) for +: 'int' and 'list'
CValueError: operands could not be broadcast together with shapes (2,) (2,3)
DNo error, result is [[2 4 4] [5 7 8]]
Attempts:
2 left
💡 Hint
Check if the shapes of the arrays can be broadcast together.
🚀 Application
advanced
2:30remaining
Using broadcasting to normalize data
You have a 2D array of data where each column needs to be normalized by subtracting the column mean. Which code correctly uses broadcasting to do this?
NumPy
import numpy as np
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Normalize columns by subtracting mean
Adata - data.mean(axis=0, keepdims=True)
Bdata - data.mean(axis=1)
Cdata - data.mean()
Ddata - data.mean(axis=0)
Attempts:
2 left
💡 Hint
Consider the shape of the mean array and how broadcasting works for subtraction.
🧠 Conceptual
expert
3:00remaining
Why broadcasting improves performance
Why does NumPy use broadcasting instead of explicit loops for operations on arrays of different shapes?
ABroadcasting forces arrays to be the same shape by copying data multiple times.
BBroadcasting allows Python to automatically parallelize code across multiple CPUs.
CBroadcasting converts arrays to lists internally for faster iteration.
DBroadcasting avoids creating large temporary arrays, saving memory and speeding up computation.
Attempts:
2 left
💡 Hint
Think about memory usage and speed when working with large data.