0
0
NumPydata~10 mins

Why broadcasting matters in NumPy - Test Your Understanding

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.dtype
B.size
C.shape
D.ndim
Attempts:
3 left
💡 Hint
Common Mistakes
Using .size instead of .shape
Trying to call .shape() as a function
2fill in blank
medium

Complete the code to add a 1D array to each row of 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 subtraction or multiplication instead of addition
Trying to add arrays with incompatible shapes without broadcasting
3fill in blank
hard

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

NumPy
import numpy as np
x = np.array([[1], [2], [3]])
y = np.array([4, 5, 6])
result = x [1] y
print(result)
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
Not understanding how broadcasting aligns dimensions
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps words to their lengths only if length is greater than 3.

NumPy
words = ['apple', 'bat', 'carrot', 'dog']
lengths = {word: [1] for word in words if [2]
Drag options to blanks, or click blank then click option'
Alen(word)
Blen(word) > 3
Cword
Dlen(words)
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself as value
Using wrong condition like len(words) instead of len(word) > 3
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps uppercase words to their lengths if length is greater than 4.

NumPy
words = ['apple', 'bat', 'carrot', 'dog']
[1] = { [2]: [3] for w in words if len(w) > 4 }
Drag options to blanks, or click blank then click option'
Aresult
Bw.upper()
Clen(w)
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'word' instead of 'w.upper()' for keys
Not assigning the comprehension to a variable