0
0
NumPydata~10 mins

Broadcasting errors and debugging 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 NumPy array of shape (3, 1).

NumPy
import numpy as np
arr = np.array([[1], [2], [3]])
print(arr[1])
Drag options to blanks, or click blank then click option'
A.shape
B.reshape(3, 1)
C.size
D.ndim
Attempts:
3 left
💡 Hint
Common Mistakes
Using .size returns total elements, not shape.
Using .ndim returns number of dimensions, not shape.
2fill in blank
medium

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

NumPy
import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6]])
B = np.array([10, 20, 30])
result = A [1] B
print(result)
Drag options to blanks, or click blank then click option'
A*
B/
C-
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using * multiplies instead of adds.
Using / causes division, not addition.
3fill in blank
hard

Fix the error in the code that tries to add arrays with incompatible shapes.

NumPy
import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6]])
B = np.array([10, 20])
result = A + B.[1](2, 1)
print(result)
Drag options to blanks, or click blank then click option'
Areshape
Bresize
Cflatten
Dravel
Attempts:
3 left
💡 Hint
Common Mistakes
flatten or ravel make B 1D, which is still incompatible.
resize modifies in place and repeats elements if necessary, not suitable here.
4fill in blank
hard

Fill both blanks to create a dictionary of word lengths for words longer than 3 characters.

NumPy
words = ['apple', 'bat', 'carrot', 'dog']
lengths = {word: [1] for word in words if len(word) [2] 3}
print(lengths)
Drag options to blanks, or click blank then click option'
Alen(word)
B>
C<
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself instead of its length.
Using less than < instead of greater than >.
5fill in blank
hard

Fill all three blanks to create a dictionary of uppercase words and their lengths for words longer than 3 characters.

NumPy
words = ['apple', 'bat', 'carrot', 'dog']
[1] = {word.[2](): [3] for word in words if len(word) > 3}
print([1])
Drag options to blanks, or click blank then click option'
Aresult
Bupper
Clen(word)
Dlower
Attempts:
3 left
💡 Hint
Common Mistakes
Using lower() instead of upper().
Not assigning the dictionary to a variable.
Using the word itself instead of its length for values.