0
0
NumPydata~10 mins

Broadcasting rules 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 2D array of shape (3, 4) filled with ones.

NumPy
import numpy as np
arr = np.ones([1])
print(arr.shape)
Drag options to blanks, or click blank then click option'
A(3, 4)
B[3, 4]
C3
D3, 4
Attempts:
3 left
💡 Hint
Common Mistakes
Using a list instead of a tuple for the shape.
Passing dimensions without parentheses.
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 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 with a (3,) array using broadcasting.

NumPy
import numpy as np
A = np.array([[1], [2], [3]])
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 addition or subtraction instead of multiplication.
Not understanding how broadcasting works with different shapes.
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 the value instead of its length.
Incorrect condition that does not filter properly.
5fill in blank
hard

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

NumPy
[1] = { [2]: [3] for word in words if len(word) > 3 }
Drag options to blanks, or click blank then click option'
Aresult
Bword
Clen(word)
Dword.upper()
Attempts:
3 left
💡 Hint
Common Mistakes
Using the original word as key instead of uppercase.
Swapping keys and values in the dictionary.
Not assigning the dictionary to a variable.