Counting distinct elements in an array in Python

Examples :

  Input: arr [] = {10, 20, 20, 10, 30, 10}   Output: 3   Input: arr [] = {10, 20, 20, 10, 20}   Output: 2  

We have a solution for Counter method.

from collections import Counter

 

def countDistinct (arr):

  

  # the counter method gives a dictionary of the items in the list

# with an appropriate frequency.

# using the keys () method of the dictionary data structure

# we can count different values ​​in the array

  return len (Counter (arr) .keys ()) 

 

if __ name__ = = "__ main__" :

arr = [ 10 , 20 , 20 , 10 , 30 , 10 ]

 < / code> print (countDistinct (arr))