Challenge - 5 Problems
np.frompyfunc Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple ufunc created with np.frompyfunc()
What is the output of this code snippet that creates a ufunc to add 10 to each element?
NumPy
import numpy as np def add_ten(x): return x + 10 ufunc_add_ten = np.frompyfunc(add_ten, 1, 1) result = ufunc_add_ten(np.array([1, 2, 3])) print(result)
Attempts:
2 left
💡 Hint
np.frompyfunc returns an object array by default.
✗ Incorrect
np.frompyfunc creates a ufunc that returns an object array containing integer values, printed as ['11' '12' '13'].
❓ data_output
intermediate2:00remaining
Result shape and type from a ufunc with multiple outputs
Given this ufunc that returns two values per input, what is the shape and type of the output when applied to a 1D array of length 3?
NumPy
import numpy as np def square_and_cube(x): return x**2, x**3 ufunc_sc = np.frompyfunc(square_and_cube, 1, 2) result = ufunc_sc(np.array([2, 3, 4])) print(type(result)) print(len(result)) print(result[0])
Attempts:
2 left
💡 Hint
np.frompyfunc returns object arrays even for multiple outputs.
✗ Incorrect
The ufunc returns a tuple of two object arrays, each containing the squared and cubed values respectively.
🔧 Debug
advanced2:00remaining
Identify the error in ufunc creation with np.frompyfunc()
What error will this code raise and why?
NumPy
import numpy as np def faulty_func(x, y): return x + y ufunc_faulty = np.frompyfunc(faulty_func, 1, 1)
Attempts:
2 left
💡 Hint
Check the number of input arguments specified vs the function definition.
✗ Incorrect
No error is raised because np.frompyfunc does not inspect or validate the Python function's signature against nin at creation time. The ufunc is created successfully, but a TypeError would occur upon calling it due to argument count mismatch.
🚀 Application
advanced2:00remaining
Using np.frompyfunc() to vectorize a string operation
You want to create a ufunc that converts strings to uppercase. Which option correctly creates and applies this ufunc to a numpy array of strings?
NumPy
import numpy as np # Your code here result = ufunc_upper(np.array(['apple', 'banana', 'cherry'])) print(result)
Attempts:
2 left
💡 Hint
Remember to call the method with parentheses to execute it.
✗ Incorrect
Option A correctly defines a lambda that calls upper() on the string, matching nin=1 and nout=1.
🧠 Conceptual
expert2:00remaining
Understanding output types of np.frompyfunc() ufuncs
Which statement about the output of ufuncs created with np.frompyfunc() is TRUE?
Attempts:
2 left
💡 Hint
np.frompyfunc wraps Python functions and cannot infer fixed dtypes.
✗ Incorrect
np.frompyfunc creates ufuncs that return object arrays because the underlying Python function can return any type.