0
0
NumPydata~10 mins

np.broadcast_to() for explicit broadcasting 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 broadcast array a to shape (3, 3).

NumPy
import numpy as np

a = np.array([1, 2, 3])
b = np.broadcast_to(a, [1])
print(b)
Drag options to blanks, or click blank then click option'
A(3, 1)
B(3,)
C(1, 3)
D(3, 3)
Attempts:
3 left
💡 Hint
Common Mistakes
Using the original shape (3,) which does not broadcast.
Using (1, 3) which only adds a new axis but does not repeat rows.
2fill in blank
medium

Complete the code to broadcast a 1D array arr to a 2D array with 4 rows and 5 columns.

NumPy
import numpy as np

arr = np.array([10, 20, 30, 40, 50])
broadcasted = np.broadcast_to(arr, [1])
print(broadcasted)
Drag options to blanks, or click blank then click option'
A(4, 5)
B(5, 4)
C(1, 5)
D(5, 1)
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the dimensions and using (5, 4) which is incorrect.
Using (1, 5) which does not add the required rows.
3fill in blank
hard

Fix the error in broadcasting a 1D array data to shape (2, 3).

NumPy
import numpy as np

data = np.array([1, 2, 3])
result = np.broadcast_to(data, [1])
print(result)
Drag options to blanks, or click blank then click option'
A(3, 2)
B(2, 2)
C(2, 3)
D(3, 3)
Attempts:
3 left
💡 Hint
Common Mistakes
Using (3, 2) which swaps dimensions and causes an error.
Using (2, 2) which does not match the original array length.
4fill in blank
hard

Fill both blanks to create a dictionary with words as keys and their lengths broadcasted only if length is greater than 3.

NumPy
words = ['apple', 'bat', 'carrot', 'dog']
lengths = {word: len(word) for word in words if len(word) [1] 3}
broadcasted = np.broadcast_to(np.array(list(lengths.values())), [2])
print(broadcasted)
Drag options to blanks, or click blank then click option'
A>
B(2, 2)
C(4, 1)
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in the filter condition.
Broadcasting to a shape that does not match the number of filtered lengths.
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase words as keys, their lengths as values, and broadcast lengths greater than 4 to shape (3, 2).

NumPy
words = ['tree', 'house', 'car', 'elephant']
lengths = {word[1]: [2] for word in words if len(word) [3] 4}
broadcasted = np.broadcast_to(np.array(list(lengths.values())), (3, 2))
print(broadcasted)
Drag options to blanks, or click blank then click option'
A.upper()
Blen(word)
C>
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Not converting words to uppercase keys.
Using the word itself instead of its length as the dictionary value.
Using '<' instead of '>' in the filter condition.