Skip to content Skip to sidebar Skip to footer

Python 3 - Find The Mode Of A List

def mode(L): shows = [] modeList = [] L.sort() length = len(L) for num in L: count = L.count(num) shows.append(count) print 'List = ',

Solution 1:

The first issue with your code is that you have a return statement inside your loop. When it is reached, the function ends and the rest of the iterations never happen. You should remove return mode and instead put return modeList at the top level of the function, after the loop ends.

The second issue is that you have very broken logic regarding the counts, indexes and values in your last loop. It works some of the time because the input you're testing with tends to have counts which are also valid indexes, but it gets it right almost by chance. What you want to do is find the maximum count, then find all the values that have that count. If you zip your input list L together with the shows list, you can avoid using indexes at all:

max_count = max(shows)
for item, count inzip(L, shows):
    if count == max_count and item notin modeList:
        print("mode =", item)
        modeList.append(item)

return modeList

While that should addresses the immediate issue you're having, I feel I should suggest an alternative implementation which will be a bit faster and more efficient (not to mention requiring much less code). Rather than using list.count to find the number of appearances of each value in the list (which is requires O(N**2) time), you can use a collections.Counter to count in O(N) time. The rest of the code can be simplified a bit as well:

from collections import Counter

defmode(L):
    counter = Counter(L)
    max_count = max(counter.values())
    return [item for item, count in counter.items() if count == max_count]

Post a Comment for "Python 3 - Find The Mode Of A List"