0
0
NumPydata~10 mins

ufunc performance considerations 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 and apply a ufunc to square each element.

NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
squared = np.[1](arr)
Drag options to blanks, or click blank then click option'
Asquare
Bsqrt
Clog
Dexp
Attempts:
3 left
💡 Hint
Common Mistakes
Using np.sqrt which calculates square root instead of square.
Using np.log or np.exp which perform logarithm or exponentiation.
2fill in blank
medium

Complete the code to apply a ufunc that adds 5 to each element of the array.

NumPy
import numpy as np
arr = np.array([10, 20, 30])
result = np.[1](arr, 5)
Drag options to blanks, or click blank then click option'
Asubtract
Bmultiply
Cadd
Ddivide
Attempts:
3 left
💡 Hint
Common Mistakes
Using np.multiply which multiplies elements instead of adding.
Using np.subtract which subtracts instead of adding.
3fill in blank
hard

Fix the error in the code to correctly apply a ufunc that computes the natural logarithm of each element.

NumPy
import numpy as np
arr = np.array([1, 10, 100])
log_values = np.[1](arr)
Drag options to blanks, or click blank then click option'
Alog10
Blog
Clog1p
Dlog2
Attempts:
3 left
💡 Hint
Common Mistakes
Using np.log10 which calculates base-10 logarithm.
Using np.log2 which calculates base-2 logarithm.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps each word to its length only if the length is greater than 3.

NumPy
words = ['data', 'science', 'ai', 'ml']
lengths = {word: [1] for word in words if [2]
Drag options to blanks, or click blank then click option'
Alen(word)
Bword
Clen(word) > 3
Dword > 3
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself as value instead of its length.
Using 'word > 3' which compares string to number and causes error.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps each uppercase word to its length only if the length is greater than 2.

NumPy
words = ['cat', 'dog', 'elephant']
result = { [1]: [2] for word in words if [3] }
Drag options to blanks, or click blank then click option'
Aword.upper()
Blen(word)
Clen(word) > 2
Dword.lower()
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase instead of uppercase for keys.
Not filtering words by length correctly.