0

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

dhilmathy
  • 2,800
  • 2
  • 21
  • 29
User1676
  • 3
  • 1
  • You can probably find a solution here: [Find the most common element in a list](//stackoverflow.com/q/1518522) – Aran-Fey Mar 16 '19 at 14:16
  • I read this forum but each of the proposed functions use functions like "max, sorted, or count, etc..." and I can't use this function because we have not learned it yet in school ... – User1676 Mar 16 '19 at 14:20
  • Did you scroll far enough to find [this answer](https://stackoverflow.com/a/1519293/1222951)? – Aran-Fey Mar 16 '19 at 14:21
  • Or [this one](https://stackoverflow.com/a/2634155/1222951). – Aran-Fey Mar 16 '19 at 14:22
  • [Another one.](https://stackoverflow.com/a/1518542/1222951) – Aran-Fey Mar 16 '19 at 14:22
  • @Aran-Fey: That last linked answer is `O(n**2)`, but your other links are good. – Rory Daulton Mar 16 '19 at 14:25
  • no because I have not learned yet: " {}", or "key", or "try" but it's good I had an answer that works and with that things I learned. thank you for your answer too – User1676 Mar 16 '19 at 14:40

1 Answers1

0

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]}")
Shay Lempert
  • 311
  • 2
  • 9