- #1
trollcast
Gold Member
- 282
- 13
Homework Statement
Find the mode from a list of numbers or find the most common string in a list of names.
Homework Equations
The Attempt at a Solution
Code:
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: