0
0
NumPydata~20 mins

Universal functions (ufuncs) in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ufunc Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of numpy ufunc with broadcasting
What is the output of this code snippet using numpy universal functions and broadcasting?
NumPy
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([[1], [2], [3]])
result = np.add(arr1, arr2)
print(result)
A
[[2 3 4]
 [3 4 5]
 [4 5 6]]
B
[[2 3 4]
 [3 4 5]
 [4 5 5]]
C
[[2 3 4]
 [3 4 5]
 [4 5 7]]
D
[[2 3 4]
 [3 5 6]
 [4 6 7]]
Attempts:
2 left
💡 Hint
Remember numpy broadcasts arrays to compatible shapes before applying ufuncs.
data_output
intermediate
2:00remaining
Result of numpy sqrt ufunc on negative values
What is the output array when applying numpy.sqrt to this array containing negative values?
NumPy
import numpy as np
arr = np.array([4, 9, -1, 16])
result = np.sqrt(arr)
print(result)
A[2. 3. -1. 4.]
B[2. 3. 1. 4.]
C[2. 3. nan 4.]
D[2. 3. 0. 4.]
Attempts:
2 left
💡 Hint
Square root of negative numbers is not defined in real numbers, numpy returns nan with a warning.
visualization
advanced
3:00remaining
Visualizing numpy ufunc output with vectorize
Which plot correctly shows the output of applying a numpy ufunc to a range of values using np.vectorize?
NumPy
import numpy as np
import matplotlib.pyplot as plt

def custom_func(x):
    return np.sin(x) if x >= 0 else 0

vec_func = np.vectorize(custom_func)
x = np.linspace(-np.pi, np.pi, 100)
y = vec_func(x)
plt.plot(x, y)
plt.title('Custom function output')
plt.show()
AA sine wave mirrored about y-axis
BA full sine wave from -pi to pi
CA flat line at zero
DA plot showing sine wave only for x >= 0 and zero for x < 0
Attempts:
2 left
💡 Hint
The function returns sine only for non-negative x, zero otherwise.
🧠 Conceptual
advanced
2:00remaining
Understanding numpy ufunc reduce method
What is the output of this code using numpy's ufunc reduce method?
NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
result = np.add.reduce(arr)
print(result)
A[1 3 6 10]
B10
C24
D[1 2 3 4]
Attempts:
2 left
💡 Hint
ufunc reduce applies the operation cumulatively to the array elements.
🔧 Debug
expert
2:30remaining
Identify the error in this numpy ufunc usage
What error does this code raise when applying numpy's power ufunc with incompatible shapes?
NumPy
import numpy as np
base = np.array([1, 2, 3])
exponent = np.array([[1, 2], [3, 4]])
result = np.power(base, exponent)
print(result)
AValueError: operands could not be broadcast together with shapes (3,) (2,2)
BNo error, outputs a 2x3 array
CIndexError: index out of bounds
DTypeError: unsupported operand type(s) for ** or pow()
Attempts:
2 left
💡 Hint
Check if the shapes of base and exponent arrays can be broadcast together.