Challenge - 5 Problems
Broadcasting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this NumPy broadcasting code?
Consider the following code snippet using NumPy arrays. What will be the output?
NumPy
import numpy as np arr1 = np.array([[1, 2, 3], [4, 5, 6]]) arr2 = np.array([1, 0, 1]) result = arr1 + arr2 print(result)
Attempts:
2 left
💡 Hint
Remember how NumPy broadcasts arrays with compatible shapes by stretching dimensions.
✗ Incorrect
The array arr2 with shape (3,) is broadcast across the rows of arr1 with shape (2,3). So each row of arr1 adds the arr2 vector element-wise.
❓ Predict Output
intermediate2:00remaining
What error does this broadcasting code raise?
What error will this code produce when run?
NumPy
import numpy as np arr1 = np.array([[1, 2], [3, 4]]) arr2 = np.array([1, 2, 3]) result = arr1 + arr2 print(result)
Attempts:
2 left
💡 Hint
Check if the shapes of the arrays can be broadcast together.
✗ Incorrect
The shapes (2,2) and (3,) are incompatible for broadcasting because the last dimensions differ and cannot be stretched to match.
🔧 Debug
advanced2:30remaining
Identify the broadcasting bug in this code
This code tries to add two arrays but raises an error. Which line causes the broadcasting error?
NumPy
import numpy as np arr1 = np.array([[1, 2, 3], [4, 5, 6]]) arr2 = np.array([[1], [2], [3]]) result = arr1 + arr2 print(result)
Attempts:
2 left
💡 Hint
Check the shapes of arr1 and arr2 before addition.
✗ Incorrect
The addition fails because arr1 has shape (2,3) and arr2 has shape (3,1). These shapes cannot be broadcast together.
❓ data_output
advanced2:00remaining
What is the shape of the result after broadcasting?
Given these arrays, what is the shape of the result after adding arr1 and arr2?
NumPy
import numpy as np arr1 = np.ones((4,1,3)) arr2 = np.ones((1,5,1)) result = arr1 + arr2 print(result.shape)
Attempts:
2 left
💡 Hint
Broadcasting works by matching dimensions from the right and stretching size 1 dimensions.
✗ Incorrect
The shapes (4,1,3) and (1,5,1) broadcast to (4,5,3) by stretching the 1s to match the other array's size.
🚀 Application
expert3:00remaining
Fix the broadcasting error to compute weighted sums
You want to compute weighted sums of rows in a 2D array using a 1D weights array. The code below raises an error. Which option fixes it correctly?
NumPy
import numpy as np values = np.array([[10, 20, 30], [40, 50, 60]]) weights = np.array([0.1, 0.2]) weighted_sum = (values * weights).sum(axis=1) print(weighted_sum)
Attempts:
2 left
💡 Hint
Make weights shape compatible with values shape (2,3) for element-wise multiplication.
✗ Incorrect
values shape is (2,3), weights shape is (2,). To multiply element-wise, weights must be reshaped to (1,2) to broadcast along rows.