0
0
NumPydata~10 mins

Avoiding temporary arrays 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, 3).

NumPy
import numpy as np
arr = np.[1]((3, 3))
Drag options to blanks, or click blank then click option'
Afull
Bones
Cempty
Dzeros
Attempts:
3 left
💡 Hint
Common Mistakes
Using np.ones instead of np.zeros
Using np.empty which creates uninitialized values
2fill in blank
medium

Complete the code to multiply two arrays element-wise without creating a temporary array.

NumPy
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = np.multiply(arr1, arr2, out=[1])
Drag options to blanks, or click blank then click option'
Aarr1
BNone
Carr2
Dresult
Attempts:
3 left
💡 Hint
Common Mistakes
Setting out to None creates a new array (temporary)
Setting out to a variable not defined yet
3fill in blank
hard

Fix the error in the code to add 5 to each element of arr without creating a temporary array.

NumPy
import numpy as np
arr = np.array([1, 2, 3])
np.add(arr, [1], out=arr)
Drag options to blanks, or click blank then click option'
Aarr
Bnp.array([5,5,5])
C5
Dnp.add
Attempts:
3 left
💡 Hint
Common Mistakes
Using arr = arr + 5 creates a temporary array
Using np.add without out parameter
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 = { [1]: [2] for word in words if len(word) > 3 }
Drag options to blanks, or click blank then click option'
Aword
Blen(word)
Cword.upper()
Dlen(word) > 3
Attempts:
3 left
💡 Hint
Common Mistakes
Using the condition as a key or value
Using word.upper() instead of word as key
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
words = ['apple', 'bat', 'carrot', 'dog']
lengths = { [1]: [2] for word in words if len(word) [3] 3 }
Drag options to blanks, or click blank then click option'
Aword.upper()
Blen(word)
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > in the condition
Using word instead of word.upper() as key