Challenge - 5 Problems
Ufunc Performance Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of ufunc with broadcasting
What is the output of this code snippet using NumPy ufunc broadcasting?
NumPy
import numpy as np arr1 = np.array([1, 2, 3]) arr2 = np.array([[10], [20], [30]]) result = np.add(arr1, arr2) print(result)
Attempts:
2 left
💡 Hint
Remember how broadcasting works when adding arrays of different shapes.
✗ Incorrect
NumPy broadcasts arr1 shape (3,) to (1,3) and arr2 shape (3,1) to (3,3). Adding them results in a 3x3 array where each element is sum of corresponding broadcasted elements.
❓ data_output
intermediate1:30remaining
Number of elements processed by ufunc
Given a NumPy ufunc applied on arrays of shapes (4, 1, 3) and (1, 5, 3), how many elements does the ufunc process in total?
Attempts:
2 left
💡 Hint
Calculate the broadcasted shape first, then multiply dimensions.
✗ Incorrect
Broadcasting shapes (4,1,3) and (1,5,3) results in (4,5,3). Total elements = 4*5*3 = 60.
🔧 Debug
advanced2:30remaining
Identify the cause of slow ufunc performance
Why does this NumPy ufunc operation run slower than expected?
Code:
import numpy as np
large_array = np.arange(10**7)
result = np.sin(large_array)
Options:
NumPy
import numpy as np large_array = np.arange(10**7) result = np.sin(large_array)
Attempts:
2 left
💡 Hint
Check the data type of the input array and how ufuncs handle types.
✗ Incorrect
np.arange creates an integer array. np.sin expects floats, so it converts each element to float before computing, adding overhead.
🚀 Application
advanced2:00remaining
Optimizing ufunc calls for large data
You want to apply np.exp to a very large array efficiently. Which approach is best to improve performance?
Attempts:
2 left
💡 Hint
Consider memory usage and cache efficiency for large arrays.
✗ Incorrect
Processing large arrays in smaller chunks fits better in cache and memory, improving performance and avoiding memory issues.
🧠 Conceptual
expert3:00remaining
Understanding ufunc inner loops and performance
Which statement best explains why NumPy ufuncs achieve high performance compared to Python loops?
Attempts:
2 left
💡 Hint
Think about how NumPy is implemented under the hood.
✗ Incorrect
NumPy ufuncs are implemented in C with tight loops that operate on raw memory, avoiding Python overhead and enabling vectorized operations.