0
0
NumPydata~10 mins

Avoiding broadcasting mistakes 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 zeros with shape (3, 4).

NumPy
import numpy as np
arr = np.[1]((3, 4))
Drag options to blanks, or click blank then click option'
Azeros
Bfull
Cempty
Dones
Attempts:
3 left
💡 Hint
Common Mistakes
Using np.ones instead of np.zeros creates an array of ones.
Using np.empty creates an uninitialized array with random values.
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
arr = np.array([[1, 2, 3], [4, 5, 6]])
add = np.array([10, 20, 30])
result = arr + [1]
Drag options to blanks, or click blank then click option'
Aadd.reshape(3, 1)
Badd
Cadd.T
Dadd.reshape(1, 3)
Attempts:
3 left
💡 Hint
Common Mistakes
Reshaping to (3, 1) tries to add column-wise, causing shape mismatch.
Using add.T does not change shape correctly for broadcasting.
3fill in blank
hard

Fix the error in the code to multiply a 2D array by a 1D array along columns using broadcasting.

NumPy
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
multiplier = np.array([2, 3])
result = arr * [1]
Drag options to blanks, or click blank then click option'
Amultiplier.reshape(2, 1)
Bmultiplier
Cmultiplier.reshape(1, 2)
Dmultiplier.T
Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplier without reshape causes shape mismatch error.
Reshaping to (1, 2) aligns with columns, not rows.
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.startswith('a')
Dword != 'dog'
Attempts:
3 left
💡 Hint
Common Mistakes
Using word.startswith('a') filters words starting with 'a' instead of length.
Using word != 'dog' excludes 'dog' but does not check length.
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 4.

NumPy
words = ['apple', 'bat', 'carrot', 'dog']
result = {{ [1]: [2] for w in words if [3] }}
Drag options to blanks, or click blank then click option'
Aw.upper()
Blen(w)
Clen(w) > 4
Dw.lower()
Attempts:
3 left
💡 Hint
Common Mistakes
Using w.lower() instead of w.upper() changes the case incorrectly.
Filtering with len(w) > 3 includes shorter words than required.