v9.1.1
Menu

Boolean Indexing

easyFREESubsetting, Slicing, IndexingNumPy IndexingNumpy

Problem Statement

Use boolean conditions to filter NumPy arrays.

Background

Boolean indexing lets you select 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:

  • "greater": Elements greater than threshold as list
  • "less_equal": Elements less than or equal to threshold as list
  • "count_greater": Count of elements greater than threshold

Output Format

Return a dictionary with exactly these three keys.

Example

Input
arr = [1, 5, 3, 8, 2, 9, 4, 7], threshold = 5
Output
{'greater': [8, 9, 7], 'less_equal': [1, 5, 3, 2, 4], 'count_greater': 3}
Reasoning
  • Input: arr is a 1D array of 8 integers, [1, 5, 3, 8, 2, 9, 4, 7], and threshold is 5. Each element is compared with the threshold on its own.
  • Comparing: testing x>5x > 5 across the array gives true, false, false, true, false, true, false, true. Only 88, 99 and 77 pass.
  • Splitting: every element falls into exactly one of two groups. x>5x > 5 gives [8, 9, 7]; x≤5x \le 5 gives [1, 5, 3, 2, 4]. The two groups together hold all 3+5=83 + 5 = 8 elements.
  • Order is preserved: each group keeps the elements in their original left-to-right positions, so 9 comes before 7 and the values are not sorted.
  • Boundary: 5 equals the threshold, so it lands in less_equal. The comparison for greater is strict.
  • Output: a dictionary whose greater and less_equal entries are plain Python lists, plus count_greater = 33, the size of the first group. If nothing exceeds the threshold, greater is [] and the count is 00.

Constraints

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

Learn this in

More from Numpy

solution.py

Test results

Sign in to run your code against the test cases.