0
0
NumPydata~20 mins

Comparison operations in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Comparison Operations Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of element-wise comparison with numpy arrays
What is the output of this code snippet using numpy arrays for comparison?
NumPy
import numpy as np
arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([2, 2, 2, 2])
result = arr1 > arr2
print(result)
A[False False True True]
B[True False False False]
C[True True True True]
D[False False False False]
Attempts:
2 left
💡 Hint
Compare each element of arr1 with the corresponding element in arr2.
data_output
intermediate
1:30remaining
Count of elements equal to a value in numpy array
Given a numpy array, how many elements are equal to 5?
NumPy
import numpy as np
arr = np.array([5, 3, 5, 7, 5, 2])
count = np.sum(arr == 5)
print(count)
A3
B2
C1
D4
Attempts:
2 left
💡 Hint
Use element-wise comparison and sum the True values.
🔧 Debug
advanced
2:00remaining
Identify the error in numpy comparison code
What error does this code raise?
NumPy
import numpy as np
arr = np.array([1, 2, 3])
result = arr > 2 > 1
print(result)
ANo error, outputs [False True True]
BTypeError: '>' not supported between instances of 'numpy.ndarray' and 'int'
CSyntaxError: invalid syntax
DValueError: The truth value of an array is ambiguous
Attempts:
2 left
💡 Hint
Check how chained comparisons work with numpy arrays.
🚀 Application
advanced
1:30remaining
Filter numpy array elements using comparison
Which option correctly filters elements greater than 10 from the numpy array?
NumPy
import numpy as np
arr = np.array([5, 12, 7, 18, 3])
filtered = ???
print(filtered)
Aarr.filter(arr > 10)
Barr > 10
Carr[arr > 10]
Dnp.filter(arr, arr > 10)
Attempts:
2 left
💡 Hint
Use boolean indexing to select elements.
🧠 Conceptual
expert
2:30remaining
Understanding broadcasting in numpy comparison
Given arr1 = np.array([1, 2, 3]) and arr2 = np.array([[2], [3], [4]]), what is the shape of the result of arr1 < arr2?
NumPy
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([[2], [3], [4]])
result = arr1 < arr2
print(result.shape)
A(1, 3)
B(3, 3)
C(3,)
D(3, 1)
Attempts:
2 left
💡 Hint
Consider how numpy broadcasts shapes (3,) and (3,1) for element-wise comparison.