1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Find most common value in an array

  1. Feb 20, 2013 #1

    trollcast

    User Avatar
    Gold Member

    1. The problem statement, all variables and given/known data
    Find the mode from a list of numbers or find the most common string in a list of names.

    2. Relevant equations

    3. The attempt at a solution

    Code (Text):
    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: Feb 20, 2013
  2. jcsd
  3. Feb 20, 2013 #2

    rcgldr

    User Avatar
    Homework Helper

    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.
     
  4. Feb 20, 2013 #3

    trollcast

    User Avatar
    Gold Member

    Sorry I should have copied more of the code.

    I've sorted the list before I pass it to the most_common_element function.
     
  5. Feb 20, 2013 #4

    rcgldr

    User Avatar
    Homework Helper

    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.
     
  6. Feb 20, 2013 #5

    trollcast

    User Avatar
    Gold Member

    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
     
  7. Feb 20, 2013 #6

    rcgldr

    User Avatar
    Homework Helper

    After your updates, the code looks OK now.
     
    Last edited: Feb 20, 2013
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Find most common value in an array
Loading...