Challenge - 5 Problems
Boolean Masking Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of boolean masking on a NumPy array
What is the output of this code snippet using boolean masking on a NumPy array?
NumPy
import numpy as np arr = np.array([10, 15, 20, 25, 30]) mask = arr > 20 result = arr[mask] print(result)
Attempts:
2 left
💡 Hint
Think about which elements are greater than 20 in the array.
✗ Incorrect
The mask selects elements greater than 20, which are 25 and 30, so the output is [25 30].
❓ data_output
intermediate1:30remaining
Number of elements selected by boolean mask
How many elements does this boolean mask select from the array?
NumPy
import numpy as np arr = np.array([5, 12, 17, 9, 3, 21]) mask = (arr >= 10) & (arr <= 20) selected = arr[mask] print(len(selected))
Attempts:
2 left
💡 Hint
Count how many numbers are between 10 and 20 inclusive.
✗ Incorrect
The numbers 12, 17, and 21 are checked, but 21 is excluded because it's > 20. So selected are 12, 17, and no others. So answer is 2.
🔧 Debug
advanced2:00remaining
Identify the error in boolean masking code
What error does this code raise when trying to apply boolean masking?
NumPy
import numpy as np arr = np.array([1, 2, 3, 4, 5]) mask = arr > 3 result = arr[mask == True] print(result)
Attempts:
2 left
💡 Hint
Check how boolean arrays compare with True in NumPy.
✗ Incorrect
Comparing a boolean array with True using '==' returns the same boolean array, so arr[mask == True] is equivalent to arr[mask]. No error occurs and output is [4 5].
🚀 Application
advanced2:30remaining
Filter and modify array elements using boolean masking
Given the array, which option correctly doubles only the elements less than 10 using boolean masking?
NumPy
import numpy as np arr = np.array([4, 11, 7, 15, 3]) # Your code here to double elements < 10
Attempts:
2 left
💡 Hint
Focus on selecting elements less than 10 and multiplying them by 2.
✗ Incorrect
Option B correctly selects elements less than 10 and doubles them in place. Others either select wrong elements or perform wrong operations.
🧠 Conceptual
expert1:30remaining
Why is boolean masking preferred over loops in NumPy?
Which reason best explains why boolean masking is preferred over explicit Python loops for filtering NumPy arrays?
Attempts:
2 left
💡 Hint
Think about speed and efficiency of operations in NumPy.
✗ Incorrect
Boolean masking leverages NumPy's optimized vectorized operations, making it much faster than explicit Python loops which are slower and less efficient.