0
0
NumPydata~10 mins

Broadcasting with higher dimensions 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 create a 3D array of zeros with shape (2, 3, 4).

NumPy
import numpy as np
arr = np.zeros([1])
print(arr.shape)
Drag options to blanks, or click blank then click option'
A(2, 3, 4)
B2, 3, 4
C[2, 3, 4]
D3, 4, 2
Attempts:
3 left
💡 Hint
Common Mistakes
Using a list instead of a tuple for the shape.
Passing separate numbers without parentheses.
2fill in blank
medium

Complete the code to add a 1D array to a 3D array using broadcasting.

NumPy
import numpy as np
arr3d = np.ones((2, 3, 4))
arr1d = np.array([1, 2, 3, 4])
result = arr3d + [1]
print(result.shape)
Drag options to blanks, or click blank then click option'
Aarr1d.reshape(1, 4)
Barr1d.reshape(4, 1)
Carr1d.reshape(1, 1, 4)
Darr1d
Attempts:
3 left
💡 Hint
Common Mistakes
Using the original 1D array without reshaping.
Reshaping to incompatible shapes like (4, 1) or (1, 4).
3fill in blank
hard

Fix the error in the code to multiply a (3, 1) array with a (1, 4) array using broadcasting.

NumPy
import numpy as np
arr1 = np.array([[1], [2], [3]])
arr2 = np.array([[4, 5, 6, 7]])
result = arr1 [1] arr2
print(result.shape)
Drag options to blanks, or click blank then click option'
A/
B+
C-
D*
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition or subtraction instead of multiplication.
Using division which would also broadcast but is not the intended operation.
4fill in blank
hard

Fill both blanks to create a 3D array by broadcasting a (3, 1) array and a (1, 4) array.

NumPy
import numpy as np
arr1 = np.array([[1], [2], [3]])
arr2 = np.array([[4, 5, 6, 7]])
result = arr1 [1] arr2
print(result.shape == ([2]))
Drag options to blanks, or click blank then click option'
A*
B+
C(3, 4)
D(4, 3)
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of multiplication.
Confusing the shape order as (4, 3) instead of (3, 4).
5fill in blank
hard

Fill all three blanks to multiply two arrays using broadcasting and verify the resulting shape.

NumPy
import numpy as np
a = np.ones((3,1))
b = np.arange(4).reshape(1,4)
result = a [1] b
print(result.shape == ([2], [3]))
Drag options to blanks, or click blank then click option'
A*
B3
C4
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using matrix multiplication @ instead of element-wise *.
Reversing the shape dimensions to (4,3).