# Homework Help: Find most common value in an array

1. Feb 20, 2013

### trollcast

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

### rcgldr

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.

3. Feb 20, 2013

### trollcast

Sorry I should have copied more of the code.

I've sorted the list before I pass it to the most_common_element function.

4. Feb 20, 2013

### rcgldr

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.

5. Feb 20, 2013

### trollcast

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

6. Feb 20, 2013

### rcgldr

After your updates, the code looks OK now.

Last edited: Feb 20, 2013