Challenge - 5 Problems
Boolean Counting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Counting True values in a boolean NumPy array
What is the output of this code snippet that counts True values in a boolean NumPy array?
NumPy
import numpy as np arr = np.array([True, False, True, True, False]) count = np.sum(arr) print(count)
Attempts:
2 left
💡 Hint
Remember that True is treated as 1 and False as 0 in NumPy when summing.
✗ Incorrect
The array has three True values. Summing treats True as 1, so the sum is 3.
❓ data_output
intermediate2:00remaining
Counting True values along an axis in a 2D boolean array
Given this 2D boolean array, what is the output of counting True values along axis 1?
NumPy
import numpy as np arr = np.array([[True, False, True], [False, False, True], [True, True, True]]) counts = np.sum(arr, axis=1) print(counts)
Attempts:
2 left
💡 Hint
Sum along axis 1 means count True values in each row.
✗ Incorrect
Row 1 has 2 True, row 2 has 1 True, row 3 has 3 True values.
🔧 Debug
advanced2:00remaining
Identify the error in counting True values with incorrect axis
What error does this code raise when trying to count True values along axis 2 in a 2D boolean array?
NumPy
import numpy as np arr = np.array([[True, False], [False, True]]) count = np.sum(arr, axis=2) print(count)
Attempts:
2 left
💡 Hint
Check the dimensions of the array and the axis argument.
✗ Incorrect
The array is 2D, so valid axes are 0 and 1. Axis 2 is invalid and causes AxisError.
🚀 Application
advanced2:00remaining
Counting values greater than a threshold using boolean arrays
Given a NumPy array of numbers, which option correctly counts how many values are greater than 10?
NumPy
import numpy as np arr = np.array([5, 12, 7, 20, 15]) count = ??? print(count)
Attempts:
2 left
💡 Hint
Create a boolean array where values are greater than 10, then sum True values.
✗ Incorrect
arr > 10 creates a boolean array. Summing counts True values, which are values > 10.
🧠 Conceptual
expert2:00remaining
Understanding boolean array counting with np.count_nonzero vs np.sum
Which statement best describes the difference between np.count_nonzero(boolean_array) and np.sum(boolean_array) when counting True values?
Attempts:
2 left
💡 Hint
Think about how True and False are treated in NumPy arithmetic and counting.
✗ Incorrect
Both functions count True values in boolean arrays, but np.count_nonzero counts non-zero elements, which are True, and np.sum adds True as 1.