Bird
Raised Fist0
NumPydata~20 mins

Broadcasting errors and debugging in NumPy - Practice Problems & Coding Challenges

Choose your learning style10 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
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)
A
[[2 2 4]
 [5 5 7]]
BValueError: operands could not be broadcast together with shapes (2,3) (3,)
C
[[2 3 4]
 [5 6 7]]
D
[[1 2 3]
 [4 5 6]]
Attempts:
2 left
💡 Hint
Remember how NumPy broadcasts arrays with compatible shapes by stretching dimensions.
❓ Predict Output
intermediate
2: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)
AValueError: operands could not be broadcast together with shapes (2,2) (3,)
BTypeError: unsupported operand type(s) for +: 'int' and 'list'
CIndexError: index 3 is out of bounds for axis 0 with size 2
D
[[2 4 4]
 [4 6 7]]
Attempts:
2 left
💡 Hint
Check if the shapes of the arrays can be broadcast together.
🔧 Debug
advanced
2: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)
ALine 5: addition operation arr1 + arr2 causes error
BLine 3: arr1 definition shape (2,3) incompatible with arr2 (3,1)
CNo error, code runs fine
DLine 4: arr2 definition shape (3,1) incompatible with arr1 (2,3)
Attempts:
2 left
💡 Hint
Check the shapes of arr1 and arr2 before addition.
❓ data_output
advanced
2: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)
A(1, 5, 3)
B(4, 1, 5, 3)
CValueError: operands could not be broadcast together
D(4, 5, 3)
Attempts:
2 left
💡 Hint
Broadcasting works by matching dimensions from the right and stretching size 1 dimensions.
🚀 Application
expert
3: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)
Aweights = weights[:, np.newaxis]
Bweights = weights[np.newaxis, :]
Cweights = weights.reshape(3, 1)
Dweights = weights.flatten()
Attempts:
2 left
💡 Hint
Make weights shape compatible with values shape (2,3) for element-wise multiplication.

Practice

(1/5)
1. What causes a broadcasting error in NumPy when working with arrays?
easy
A. When arrays contain only zeros
B. When arrays have the same shape
C. When array shapes are not compatible for element-wise operations
D. When arrays are one-dimensional

Solution

  1. Step 1: Understand broadcasting rules

    Broadcasting requires arrays to have compatible shapes, meaning dimensions must be equal or one of them is 1.
  2. Step 2: Identify cause of error

    If shapes cannot be matched or stretched to match, a broadcasting error occurs.
  3. Final Answer:

    When array shapes are not compatible for element-wise operations -> Option C
  4. Quick Check:

    Broadcasting error = incompatible shapes [OK]
Hint: Check if array shapes can align or stretch [OK]
Common Mistakes:
  • Assuming arrays with same number of elements always broadcast
  • Ignoring dimension sizes when broadcasting
  • Thinking zeros cause broadcasting errors
2. Which of the following NumPy operations will cause a broadcasting error?
easy
A. np.array([1, 2, 3]) + np.array([[1, 2], [3, 4]])
B. np.array([1, 2, 3]) + np.array([4, 5, 6])
C. np.array([1, 2, 3]) + np.array([[1], [2], [3]])
D. np.array([[1], [2], [3]]) + np.array([4])

Solution

  1. Step 1: Check shapes of arrays in each option

    np.array([1, 2, 3]) + np.array([[1, 2], [3, 4]]) adds shape (3,) and (2,2), which are incompatible for broadcasting.
  2. Step 2: Confirm broadcasting compatibility

    Other options have compatible shapes: (3,) and (3,1), (3,) and (3,), (3,1) and (1,).
  3. Final Answer:

    np.array([1, 2, 3]) + np.array([[1, 2], [3, 4]]) -> Option A
  4. Quick Check:

    Shape mismatch causes error [OK]
Hint: Compare array shapes dimension-wise from right [OK]
Common Mistakes:
  • Ignoring that (3,) and (2,2) cannot broadcast
  • Confusing 1D and 2D shapes
  • Assuming all arrays add without error
3. What is the output of this code?
import numpy as np
x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.array([10, 20])
result = x + y
print(result)
medium
A. Broadcasting error
B. [[11 12 13] [14 15 16]]
C. [[11 12 13] [24 25 26]]
D. [[11 22 13] [14 25 16]]

Solution

  1. Step 1: Check shapes of x and y

    x shape is (2,3), y shape is (2,). These shapes are not compatible for broadcasting because trailing dimensions differ and y cannot be stretched to match x.
  2. Step 2: Predict result of x + y

    Since shapes are incompatible, NumPy raises a broadcasting error.
  3. Final Answer:

    Broadcasting error -> Option A
  4. Quick Check:

    Shape (2,3) + (2,) = error [OK]
Hint: Match shapes from right; trailing dims must be equal or 1 [OK]
Common Mistakes:
  • Assuming (2,) broadcasts to (2,3)
  • Expecting element-wise addition without shape check
  • Ignoring broadcasting rules for 2D arrays
4. You get a broadcasting error when adding arrays a with shape (3, 1) and b with shape (3,). How can you fix it?
medium
A. Reshape a to (3,) before adding
B. No fix needed; shapes are compatible
C. Transpose a to (1, 3) before adding
D. Reshape b to (3, 1) before adding

Solution

  1. Step 1: Analyze shapes

    a (3,1), b (3,): pad b to (1,3). Trailing: 1 vs 3 (1 stretches), leading: 3 vs 1 (1 stretches). Compatible, result shape (3,3).
  2. Step 2: No error occurs

    Direct addition works fine.
  3. Final Answer:

    No fix needed; shapes are compatible -> Option B
  4. Quick Check:

    (3,1) + (3,) works [OK]
Hint: Verify compatibility: pad lower-rank with leading 1s [OK]
Common Mistakes:
  • Thinking (3,1) + (3,) errors
  • Reshaping when automatic broadcasting works
  • Confusing padding position
5. You have a 3D array arr with shape (4, 1, 5) and a 2D array mat with shape (1, 3). You want to add them without error. What is the correct way?
hard
A. Add directly; broadcasting works automatically
B. Reshape arr to (4, 3, 5) before adding
C. Reshape mat to (1, 1, 3) before adding
D. Reshape mat to (1, 3, 1) before adding

Solution

  1. Step 1: Check shapes and broadcasting rules

    arr shape: (4,1,5), mat shape: (1,3). To add, shapes must be compatible from right: 5 vs missing, 1 vs 3, 4 vs 1.
  2. Step 2: Reshape mat to match arr's dimensions

    Reshape mat to (1,3,1) so shapes become (4,1,5) and (1,3,1), compatible for broadcasting.
  3. Final Answer:

    Reshape mat to (1, 3, 1) before adding -> Option D
  4. Quick Check:

    Match dimensions by adding missing axis [OK]
Hint: Add missing dimensions with reshape for broadcasting [OK]
Common Mistakes:
  • Assuming direct add works without reshape
  • Reshaping arr incorrectly
  • Confusing dimension order in reshape
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard