0
0
NumPydata~10 mins

np.frompyfunc() for ufunc creation 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 ufunc from a Python function that adds 5 to a number.

NumPy
import numpy as np

def add_five(x):
    return x + 5

add_five_ufunc = np.frompyfunc(add_five, 1, [1])
result = add_five_ufunc(10)
print(result)
Drag options to blanks, or click blank then click option'
A3
B1
C0
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Setting the number of outputs to 2 or 0 causes errors because the function returns only one value.
2fill in blank
medium

Complete the code to create a ufunc that takes two inputs and returns their product.

NumPy
import numpy as np

def multiply(x, y):
    return x * y

multiply_ufunc = np.frompyfunc(multiply, [1], 1)
result = multiply_ufunc(3, 4)
print(result)
Drag options to blanks, or click blank then click option'
A2
B1
C3
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Setting the number of inputs to 1 or 3 causes errors because the function expects exactly two inputs.
3fill in blank
hard

Fix the error in the code by completing the blank with the correct number of outputs for the ufunc.

NumPy
import numpy as np

def split_number(x):
    return x // 10, x % 10

split_ufunc = np.frompyfunc(split_number, 1, [1])
result = split_ufunc(34)
print(result)
Drag options to blanks, or click blank then click option'
A2
B1
C3
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Setting the number of outputs to 1 causes the ufunc to return a tuple inside one output, which is not intended.
4fill in blank
hard

Fill both blanks to create a ufunc that returns True if the first number is greater than the second.

NumPy
import numpy as np

def is_greater(x, y):
    return x [1] y

greater_ufunc = np.frompyfunc(is_greater, [2], 1)
result = greater_ufunc(5, 3)
print(result)
Drag options to blanks, or click blank then click option'
A>
B2
C==
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong comparison operator changes the logic of the function.
Setting the number of inputs incorrectly causes errors.
5fill in blank
hard

Fill both blanks to create a dictionary with the word and its length if length is greater than 3.

NumPy
words = ['cat', 'elephant', 'dog']
lengths = {word: [1] for word in words if len(word) [2] 3}
print(lengths)
Drag options to blanks, or click blank then click option'
A{
Blen(word)
C>
D[
Attempts:
3 left
💡 Hint
Common Mistakes
Using square brackets instead of curly braces for dictionary comprehension.
Using wrong comparison operators like < or ==.