Challenge - 5 Problems
Comparison Operations Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Compare each element of arr1 with the corresponding element in arr2.
✗ Incorrect
The comparison arr1 > arr2 checks each element: 1>2 is False, 2>2 is False, 3>2 is True, 4>2 is True, resulting in [False False True True].
❓ data_output
intermediate1: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)
Attempts:
2 left
💡 Hint
Use element-wise comparison and sum the True values.
✗ Incorrect
The expression arr == 5 creates a boolean array [True, False, True, False, True, False]. Summing True values (counted as 1) gives 3.
🔧 Debug
advanced2: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)
Attempts:
2 left
💡 Hint
Check how chained comparisons work with numpy arrays.
✗ Incorrect
The expression arr > 2 > 1 is evaluated as (arr > 2) > 1. The first part returns a boolean array, then Python tries to compare this array to 1, which is invalid and raises a ValueError.
🚀 Application
advanced1: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)
Attempts:
2 left
💡 Hint
Use boolean indexing to select elements.
✗ Incorrect
Boolean indexing with arr[arr > 10] returns elements where the condition is True. Other options are invalid or return boolean arrays instead of filtered elements.
🧠 Conceptual
expert2: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)
Attempts:
2 left
💡 Hint
Consider how numpy broadcasts shapes (3,) and (3,1) for element-wise comparison.
✗ Incorrect
arr1 shape is (3,), arr2 shape is (3,1). Broadcasting expands arr1 to (1,3) and arr2 to (3,1), resulting in a (3,3) boolean array after comparison.