Find most common value in an array

  • Thread starter Thread starter trollcast
  • Start date Start date
  • Tags Tags
    Array Value
AI Thread Summary
The discussion focuses on finding the mode in a list of numbers or names using Python. A provided code snippet attempts to identify the most common element but initially contains a mistake by initializing the variable for storing the most common elements incorrectly. Participants suggest improvements for clarity and efficiency, noting that the code should handle the frequency of elements across the entire list rather than just consecutive occurrences. The conversation highlights the importance of proper variable initialization and code readability. Overall, the code is deemed acceptable after corrections are made.
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:

Similar threads

Back
Top