v9.1.1
Menu

Unique and Count

easyFREEMiscNumPy UtilitiesNumpy

Problem Statement

Find unique elements and their counts in a NumPy array.

Background

  • np.unique(arr): Returns sorted unique elements
  • np.unique(arr, return_counts=True): Also returns count of each element

Your Task

Write a function unique_count(arr) that returns a dictionary with:

  • "unique": Unique elements (sorted) as list
  • "counts": Count of each unique element as list
  • "num_unique": Number of unique elements

Output Format

Return a dictionary with exactly these three keys.

Example

Input
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
Output
{'unique': [1, 2, 3, 4], 'counts': [1, 2, 3, 4], 'num_unique': 4}
Reasoning
  • Input: arr is a 1D array of 10 integers, [1,2,2,3,3,3,4,4,4,4][1, 2, 2, 3, 3, 3, 4, 4, 4, 4]. Values may repeat and need not arrive in order.
  • Distinct values: collapsing repeats leaves the set {1,2,3,4}\{1, 2, 3, 4\}; written in ascending order this is the unique list [1, 2, 3, 4].
  • Frequencies: for each distinct value vv, count how many positions hold it: c1=1c_1 = 1, c2=2c_2 = 2, c3=3c_3 = 3, c4=4c_4 = 4. Listed in the same order as the values, that gives counts = [1, 2, 3, 4].
  • Size: num_unique is the number of distinct values, ∣{1,2,3,4}∣=4|\{1,2,3,4\}| = 4, a plain integer rather than a list.
  • Check: the counts must add back to the input length: 1+2+3+4=101 + 2 + 3 + 4 = 10.
  • Notice that the kk-th count belongs to the kk-th unique value; here they happen to coincide, but for [5,5,5,5,5][5, 5, 5, 5, 5] you'd get unique [5] with counts [5] and num_unique 1. All three entries are plain Python lists/integers, not arrays.

Constraints

  • Use np.unique() with return_counts=True
  • Array will have at least 1 element

More from Numpy

solution.py

Test results

Sign in to run your code against the test cases.