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 Counter
def mode(L):
counter = Counter(L)
max_count = max(counter.values())
return [item for item, count in counter.items() if count == max_count]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…