Challenge - 5 Problems
Generalized ufuncs Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple generalized ufunc call
What is the output of this code using a generalized ufunc with specified core dimensions?
NumPy
import numpy as np def my_func(x, y): return x + y my_gufunc = np.frompyfunc(my_func, 2, 1) x = np.array([[1, 2], [3, 4]]) y = np.array([[10, 20], [30, 40]]) result = my_gufunc(x, y) print(result)
Attempts:
2 left
💡 Hint
Think about what the function does element-wise on the arrays.
✗ Incorrect
The generalized ufunc applies the function element-wise, adding corresponding elements of x and y.
❓ data_output
intermediate1:30remaining
Shape of output from a generalized ufunc with core dimensions
Given the following generalized ufunc call, what is the shape of the output array?
NumPy
import numpy as np def func(a, b): return a * b my_gufunc = np.frompyfunc(func, 2, 1) x = np.ones((3, 4)) y = np.ones((3, 4)) result = my_gufunc(x, y) print(result.shape)
Attempts:
2 left
💡 Hint
The function is applied element-wise to arrays of the same shape.
✗ Incorrect
The output shape matches the input arrays shape because the function operates element-wise.
🔧 Debug
advanced2:00remaining
Identify the error in this generalized ufunc definition
What error does this code raise when trying to create a generalized ufunc with core dimensions?
NumPy
import numpy as np def my_func(x, y): return x + y # Incorrect core dimensions specification my_gufunc = np.frompyfunc(my_func, 2, 1) x = np.array([1, 2, 3]) y = np.array([4, 5, 6]) result = my_gufunc(x, y) print(result)
Attempts:
2 left
💡 Hint
Check the capabilities of np.frompyfunc regarding core dimensions.
✗ Incorrect
np.frompyfunc creates simple ufuncs without support for core dimensions, so specifying them causes a TypeError.
🚀 Application
advanced2:30remaining
Using a generalized ufunc to compute matrix multiplication
Which option correctly uses a generalized ufunc to perform matrix multiplication on two 2D arrays?
NumPy
import numpy as np def matmul(a, b): return a @ b # Assume my_gufunc is defined here A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) result = my_gufunc(A, B) print(result)
Attempts:
2 left
💡 Hint
Generalized ufuncs with core dimensions require a signature to specify input/output shapes.
✗ Incorrect
np.vectorize with a signature allows specifying core dimensions for matrix multiplication, unlike frompyfunc.
🧠 Conceptual
expert1:30remaining
Understanding core dimensions in generalized ufuncs
Which statement best describes the role of core dimensions in a generalized ufunc?
Attempts:
2 left
💡 Hint
Think about how generalized ufuncs handle arrays with different shapes.
✗ Incorrect
Core dimensions are the fixed dimensions the ufunc processes directly; other dimensions are broadcasted over.