Home > Software design >  Unique integers and their counts in a list (making a histogram)
Unique integers and their counts in a list (making a histogram)

Time:01-29

If I have a list like [10, 10, 2, 3, 1], how do I determine the unique values and the counts of each unique value? For example, the result should tell me that the unique values are 10, 2, 3, 1 (i'm sure it would best if sorted) and then that the counts for each respective element is 2, 1, 1, 1.

My current solutions are as follows, though during an interview, the interviewer seemed to indicate these were not what he was looking for:

arr = [10, 10, 2, 3, 1]

# Using numpy... this is what I would actually use in practice
# could also use `np.hist` aand set the number of bins
# equal to to the number of unique elements??
unique, counts = np.unique(arr, return_counts=True)
histogram = zip(unique, counts)
# Should sort the elements of the array here... not sure
# which sorting algorithm to use and I haven't implemented
# one from scratch in a long time anyways so wouldn't know where
# to start
arr = sorting_algorithm(arr)

# Using a python dictionary
histogram = dict()
for ele in arr:
  if ele not in arr:
    histogram[ele] = 1
  else:
    histogram[ele]  = 1

CodePudding user response:

You can do this easily with a dictionary.

numberCountDic = {}

arr = [10, 10, 2, 3, 1]

for num in arr:
    # If number not in dictionary add it with count 1
    if num not in numberCountDic:
        numberCountDic[num]=1
    # Number is in dictionary already so inc the count
    else:
        numberCountDic[num] =1
        
        
print(numberCountDic)

Output

{10: 2, 2: 1, 3: 1, 1: 1}

CodePudding user response:

I would suggest using Counter from the collections module.

from collections import Counter

arr = [10, 10, 2, 3, 1]

c = Counter(arr)

for k, v in c.items():
  print(k, v)

**Output: **

10 2
2 1
3 1
1 1

CodePudding user response:

You should use collections.Counter. numpy isn't necessary here.

import collections

arr = [10, 10, 2, 3, 1]
counters = collections.Counter(arr)
print(counters) # Gets frequencies.
print(list(sorted((key, value) for key, value in counters.items()))) # Obtain sorted list by key value.
  •  Tags:  
  • Related