0
0
NumPydata~10 mins

1D and 2D broadcasting in NumPy - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to add a 1D array to each row of a 2D array using broadcasting.

NumPy
import numpy as np
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
arr_1d = np.array([10, 20, 30])
result = arr_2d + [1]
print(result)
Drag options to blanks, or click blank then click option'
Aarr_1d
Barr_2d
Cnp.array([1, 2])
Dnp.array([[10], [20], [30]])
Attempts:
3 left
💡 Hint
Common Mistakes
Adding the 2D array to itself instead of the 1D array.
Using a 2D array with incompatible shape for broadcasting.
2fill in blank
medium

Complete the code to multiply a 2D array by a 1D array using broadcasting along columns.

NumPy
import numpy as np
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
arr_1d = np.array([2, 3])
result = arr_2d * [1]
print(result)
Drag options to blanks, or click blank then click option'
Aarr_1d.reshape(3, 1)
Barr_1d.reshape(2, 1)
Carr_1d.reshape(1, 2)
Darr_1d
Attempts:
3 left
💡 Hint
Common Mistakes
Multiplying without reshaping causing shape mismatch error.
Reshaping to wrong dimensions that don't broadcast correctly.
3fill in blank
medium

Complete the code to add a 1D array to each column of a 2D array using broadcasting.

NumPy
import numpy as np
arr_2d = np.array([[1, 2], [3, 4], [5, 6]])
arr_1d = np.array([10, 20, 30])
result = arr_2d + [1]
print(result)
Drag options to blanks, or click blank then click option'
Aarr_1d.reshape(3, 1)
Barr_1d
Carr_1d.reshape(1, 3)
Darr_1d.reshape(3, 2)
Attempts:
3 left
💡 Hint
Common Mistakes
Using arr_1d directly, causing a broadcasting error.
Reshaping to dimensions that don't align properly.
4fill in blank
hard

Fix the error in the code to subtract a 1D array from each column of a 2D array using broadcasting.

NumPy
import numpy as np
arr_2d = np.array([[5, 10, 15], [20, 25, 30]])
arr_1d = np.array([1, 2])
result = arr_2d - [1]
print(result)
Drag options to blanks, or click blank then click option'
Aarr_1d
Barr_1d.reshape(1, 2)
Carr_1d.reshape(3, 1)
Darr_1d.reshape(2, 1)
Attempts:
3 left
💡 Hint
Common Mistakes
Using the 1D array without reshaping causing broadcasting error.
Reshaping to (1, 2) which aligns incorrectly for subtraction.
5fill in blank
hard

Complete the code to compute the outer product of two arrays using broadcasting (no explicit reshape needed).

NumPy
import numpy as np
a = np.array([[1], [2]])
b = np.array([[10, 20, 30]])
result = a * [1]
print(result)
Drag options to blanks, or click blank then click option'
Ab.reshape(3, 1)
Ba
Cb
Dnp.outer(a[:,0], b[0,:])
Attempts:
3 left
💡 Hint
Common Mistakes
Attempting to reshape when not needed.
Confusing the order of multiplication or using np.outer explicitly.