Python Program for Counting Distinct Elements in an Array

Python Program for Counting Distinct Elements in an Array

Counting Distinct Elements in Python

Here, in this page we will discuss the program for counting distinct elements in python programming language. We are given with an array and need to print the count of distinct element present in the given array.

Here, we will discuss two different methods to count the unique element in the given input array and compare there time and space complexity of these two methods.

  • Method 1 : Using Two loops
  • Method 2 : Using Dictionary

Method 1 :

In this method we will count the frequency of each elements using two for loops.

  • To check the status of visited elements create a array of size n and a variable say count_dis=0 which will count all distinct elements.
  • Run a loop from index 0 to n and check if (visited[i]==1) then skip that element.
  • Run a loop from index i+1 to n
  • Check if(arr[i]==arr[j]), then set visited[j]=1.
  • After complete iteration of inner for loop, increment the value of count_dis by 1.
  • At last print the value of count_dis.

Time and Space Complexity :

  • Time Complexity : O(n2)
  • Space Complexity : O(n)

Method 1 : Code in Python

Run
# Python 3 program to count unique elements
def count(arr, n):

   # Mark all array elements as not visited
    visited = [False for i in range(n)]
    count_dis=0

   # Traverse through array elements
   # and count frequencies
    for i in range(n):
     # Skip this element if already
     # processed
        if (visited[i] == True):
          continue

     # Count frequency
        for j in range(i + 1, n, 1):
            if (arr[i] == arr[j]):
                visited[j] = True
         
        count_dis = count_dis+1;
   
    print(count_dis)

# Driver Code
arr = [10, 30, 40, 20, 10, 20, 50, 10]
n = len(arr)
count(arr, n)

Output

5

Method 2 :

In this method we will count use dictinary to count the frequency of each elements and then check if that frequency is equal to 1 or not.

  • Declare a dictionary dict() and a variable say count_dis=0.
  • Start iterating over the entire array
  • If element is present in map, then increase the value of frequency by 1.
  • Otherwise, insert that element in map.
  • After complete iteration over array, start traversing map and check if value is equal to 1, if it is then increment the value of  count_dis by 1.
  • At last print the value of count_dis.

Time and Space Complexity :

  • Time Complexity : O(n)
  • Space Complexity : O(n)

Method 2 : Code in Python

Run
def count(arr, n):

    mp = dict()
    count_dis=0
    # Traverse through array elements
    # and count frequencies

    for i in range(n):
        if arr[i] in mp.keys():
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1

    print(len(mp))

# Driver Code 
arr = [10, 30, 40, 20, 10, 20, 50, 10] 
n = len(arr) 
count(arr, n)

Output

5

6 comments on “Python Program for Counting Distinct Elements in an Array”


  • Sanjeet

    //Try this in C:
    #include
    int main()
    {
    int arr[100],i,j,n,temp,loc,count=1;
    printf(“Enter the size of array: “);
    scanf(“%d”,&n);
    printf(“Enter the value in array :\n”);
    for(i=0;i<n;i++)
    {
    scanf("%d",&arr[i]);
    }
    //short array using insertion sort
    for(i=1;i<=n;i++)
    {
    temp=arr[i];
    loc=i-1;
    while(temp=0)
    {
    if(arr[loc]>temp)
    {
    arr[loc+1]=arr[loc];
    loc=loc-1;
    }
    }
    arr[loc+1]=temp;
    }
    //distinct elements
    for(i=0;i<n-1;i++)
    {
    if(arr[i]==arr[i+1])
    {
    continue;
    }
    else
    {
    count=count+1;
    }
    }
    printf("\nThe Distinct elements is: %d",count);
    return 0;
    }


  • Parvez

    size = int(input(‘Enter the size of array’))
    lst = []

    print(‘Enter the elements’)
    for i in range(size):
    element = int(input())
    lst.append(element)

    setLst = list(set(lst))
    n = len(setLst)

    count = 0
    for i in range(n):
    while i < n:
    count += 1
    break
    print(count)


  • Vishnukant

    x=int(input())
    y=[]
    for i in range(x):
    y.append(int(input()))
    z=set(y)
    c=list(z)
    print(“unqiue element qre”,len(c))


  • Arun

    from array import *
    arr=array(“i”,map(int,input(“ENTER ARRAY ELEMENTS “).split()))
    a=set(arr)
    print(len(a))


  • KIRA

    Or:

    x = [1, 2, 2, 5, 5]
    count = 0
    y = set(x)
    z = list(y)

    for i in y:
    count += 1

    print(“Elements are : {}”.format(z))
    print(“Distinct elements : {}”.format(count))