Search code examples
pythonlistmode

Python : most frequent element (mode) of sorted list without use any fonction


I went around many forums without finding my solution because most uses at least one pre-function.

I must return the statistical mode of a sorted list. Warning, because I can't use any function, like: Max, Count, key, set.

My function be in o(n)

I try with my own fonction :

def mode_liste (lis_resultat):
    """lis_resultat: sorted list"""

    d=0
    e=0
    for i in range (len(lis_resultat)-1,1,-1):
        if (lis_resultat[i]==lis_resultat[i-1]):
            e+=1
        else:
            if (d<=e):
                res=lis_resultat[i-1]
                d=e
                e=0
    return res

But this function don't work with a list of less than 2 items, and I know that it's not the good solution


Solution

  • my solution with lis being the list operated upon:

    counter = 0
    my_max = 0
    max_index = 0
    
    if len(lis) == 1:
        my_max = 1
        max_index = 0
    else:
        for i in range(1,len(lis)):
            if lis[i] == lis[i-1]:
                counter += 1
            else:
                counter = 1
            if counter > my_max:
                my_max = counter
                max_index = i
    
    print(f"occurences: {my_max},mode: {lis[max_index]}")