0
0
NumPydata~10 mins

Scalar and array 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 add a scalar value 5 to each element of the array.

NumPy
import numpy as np
arr = np.array([1, 2, 3])
result = arr [1] 5
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.
Using division or subtraction which changes values differently.
2fill in blank
medium

Complete the code to multiply each element of the array by 10 using broadcasting.

NumPy
import numpy as np
arr = np.array([4, 5, 6])
result = arr [1] 10
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.
Using floor division which truncates the result.
3fill in blank
hard

Fix the error in the code to subtract 3 from each element of the array using broadcasting.

NumPy
import numpy as np
arr = np.array([7, 8, 9])
result = arr [1] 3
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 subtraction.
Using multiplication or division which changes values differently.
4fill in blank
hard

Fill both blanks to create a new array where each element is the original element divided by 2 and then added to 4.

NumPy
import numpy as np
arr = np.array([2, 4, 6])
result = (arr [1] 2) [2] 4
print(result)
Drag options to blanks, or click blank then click option'
A/
B+
C*
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up addition and subtraction operators.
Forgetting parentheses causing wrong order of operations.
5fill in blank
hard

Fill all three blanks to create a dictionary where keys are the original array elements squared, values are the elements multiplied by 3, but only include elements greater than 2.

NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
result = { [1]: [2] for x in arr if x [3] 2 }
print(result)
Drag options to blanks, or click blank then click option'
Ax**2
Bx*3
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using less than instead of greater than in the condition.
Mixing up keys and values in the dictionary comprehension.