how many times a number is repeated in an array code example

Example: count of duplicate number in array

def FirstOccurrence ( array, n ) :
    
    beg = 0
    end = len(array) - 1

    while (beg <= end) :

        mid = int (beg + (end-beg)/2)

        if (array[mid] == n) :
            if (mid-1 >= 0 and array[mid-1] == n) :
               end = mid-1
               continue

            return mid 

        elif (array[mid] < n) :
            beg = mid + 1 
        else :
            end = mid - 1 

    return -1  

def LastOccurrence (array, n) :
    
    beg = 0
    end = len(array)-1

    while (beg <= end) :

        mid = int(beg + (end-beg)/2)

        if (array[mid] == n) :
            if (mid+1 < len(array) and array[mid+1] == n) :
               beg = mid + 1 
               continue
            return mid 

        elif (array[mid] < n) :
            beg = mid + 1 
        else :
            end = mid - 1

    return -1; 

array = [ 1, 2, 3, 9, 9, 9, 9, 10, 10, 12, 13 ]
n = int (input("Enter the number : "))

first_index = FirstOccurrence (array, n)
last_index  = LastOccurrence (array, n)

if (first_index == -1 or last_index == - 1) :
    print("Element does not exist")
else :
    print("First occurrence of " + str(n) + " is at index : " + str(first_index))
    print("Last occurrence of " + str(n) + " is at index : " + str(last_index))
    print("Total count : "+ str(last_index - first_index + 1))

Tags:

Misc Example