0
0
NumPydata~10 mins

Common broadcasting patterns 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
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
arr1d = np.array([10, 20, 30])
result = arr2d [1] arr1d
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 of incompatible shapes without broadcasting.
2fill in blank
medium

Complete the code to multiply a 2D array by a column vector using broadcasting.

NumPy
import numpy as np
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
col_vec = np.array([[10], [20]])
result = arr2d [1] col_vec
print(result)
Drag options to blanks, or click blank then click option'
A-
B+
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of multiplication.
Not reshaping the column vector properly.
3fill 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
arr2d = np.array([[5, 10], [15, 20], [25, 30]])
arr1d = np.array([1, 2, 3])
result = arr2d - arr1d[1]
print(result)
Drag options to blanks, or click blank then click option'
A.reshape(3,)
B.reshape(1, 3)
C.reshape(3, 1)
D.reshape(1, 1)
Attempts:
3 left
💡 Hint
Common Mistakes
Reshaping to (3,1) which aligns as a column vector, not row.
Not reshaping at all causing shape mismatch error.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps words to their lengths only if the 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
Clen(word) < 3
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself as the value instead of its length.
Using the wrong condition for filtering.
5fill in blank
hard

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

NumPy
words = ['hi', 'hello', 'yes', 'no']
result = { [1]: [2] for word in words if [3] }
Drag options to blanks, or click blank then click option'
Aword.upper()
Blen(word)
Clen(word) > 2
Dword.lower()
Attempts:
3 left
💡 Hint
Common Mistakes
Using word.lower() instead of word.upper().
Not filtering words by length properly.