v9.1.1
Menu

Boolean Masking

easyFREEIndexing & SlicingNumPy BooleanNumPy Foundations

Problem Statement

Use boolean conditions to filter NumPy arrays.

Background

Boolean indexing selects elements based on conditions:

arr[arr > 5]  # All elements greater than 5
arr[arr % 2 == 0]  # All even elements

Your Task

Write a function filter_array(arr, threshold) that returns a dictionary with:

  • "above": Elements strictly greater than threshold (as list)
  • "below_eq": Elements less than or equal to threshold (as list)
  • "count_above": Count of elements above threshold

Example

Input
arr = [1, 5, 3, 8, 2, 9, 4, 7], threshold = 5
Output
{'above': [8, 9, 7], 'below_eq': [1, 5, 3, 2, 4], 'count_above': 3}
Reasoning
  • Inputs: arr is a 1D array of eight integers, [1,5,3,8,2,9,4,7][1, 5, 3, 8, 2, 9, 4, 7], and threshold is the number t=5t = 5 that every element is compared against.
  • The test: for each element xix_i, ask one yes/no question: is xi>5x_i > 5? The answers, position by position, are no, no, no, yes, no, yes, no, yes.
  • above: keep the elements that answered yes, in their original order: 8,9,78, 9, 7. Order is preserved, not sorted, which is why 99 sits between 88 and 77.
  • below_eq: the complement, every xi≤5x_i \le 5: 1,5,3,2,41, 5, 3, 2, 4. Notice the 55 lands here, because 5>55 > 5 is false; the two groups split the array with no overlap and no gaps (3+5=83 + 5 = 8 elements).
  • count_above: the number of yes answers, 33, a plain whole number.
  • Output: {'above': [8, 9, 7], 'below_eq': [1, 5, 3, 2, 4], 'count_above': 3}, with both groups as ordinary Python lists. If no element exceeds the threshold, above is [] and the count is 00.

Constraints

  • Use boolean indexing arr[condition]
  • threshold will be a number

More from NumPy Foundations

solution.py

Test results

Sign in to run your code against the test cases.