def mode(L):shows = []modeList = []L.sort()length = len(L)for num in L:count = L.count(num)shows.append(count)print 'List = ', LmaxI = shows.index(max(shows))for i in shows:if i == maxI:if modeList == []:mode = L[i]modeList.append(mode)print 'Mode = ', modeelif mode not in modeList:mode = L[i]modeList.append(mode)print 'Mode = ', modereturn modemode(L)
I can't seem to iterate through my list properly...
I can successfully get the first Mode to return Mode = 87
using the 2nd for-loop however, I can't get it to search the rest of the list so that it will also return Mode = 92
I've deleted my attempts at Mode = 92
, can someone help fill in the blanks?
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 in zip(L, shows):if count == max_count and item not in 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 Counterdef mode(L):counter = Counter(L)max_count = max(counter.values())return [item for item, count in counter.items() if count == max_count]