Find most common value in an array

  • Thread starter Thread starter trollcast
  • Start date Start date
  • Tags Tags
    Array Value
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
5 replies · 2K views
trollcast
Gold Member
Messages
282
Reaction score
13

Homework Statement


Find the mode from a list of numbers or find the most common string in a list of names.

Homework Equations



The Attempt at a Solution



Code:
def most_common_element(lst):
    lst.sort()
    mostcommon = []
    mostcommonfreq = 0
    prev = 0
    count = 0

    for e in lst:
        if e != prev:
            count = 1
        if e == prev:
            count += 1

        if count == mostcommonfreq:
            mostcommon.append(e)

        if count > mostcommonfreq:
            mostcommon = [e]
            mostcommonfreq = count
        prev = e

    return mostcommon

Is there any way to make that more efficient?
 
Last edited:
Physics news on Phys.org
I'm not that familiar with python (assuming this is python), but it appears that this program finds the element that occurs the most times in a row, as opposed to the most times in the list.
 
rcgldr said:
I'm not that familiar with python (assuming this is python), but it appears that this program finds the element that occurs the most times in a row, as opposed to the most times in the list.

Sorry I should have copied more of the code.

I've sorted the list before I pass it to the most_common_element function.
 
Since the list is sorted your code looks ok. I noticed that you initialized mostcommon = 0 as opposed to mostcommon = [] (to create an empty list). It might make the code easier to follow using mostcommon = [], since the reader will know that mostcommon is to be used as a list.
 
rcgldr said:
Since the list is sorted your code looks ok. I noticed that you initialized mostcommon = 0 as opposed to mostcommon = [] (to create an empty list). Is this OK to do in Python?

Nope, I copied the source code from my program and then had to change it a bit so it made sense outside of the program.

I fixed it now
 
trollcast said:
I fixed it now
After your updates, the code looks OK now.
 
Last edited: