Here's a naive (non-optimal but very simple) solution using max
and count
:
>>> def mode(nums):
... return max(nums, key=nums.count)
...
>>> mode([1, 2, 3, 3, 4])
3
The more efficient solution (because it doesn't require iterating over nums
once per item in nums
) is indeed to use a counter. Your code mostly does this, but doesn't actually return the result:
>>> def mode(nums):
... counter = {}
... for i in nums:
... counter[i] = counter.get(i, 0) + 1
... return max(counter, key=counter.get)
...
>>> mode([1, 2, 3, 3, 4])
3
Note that the statistics
module is built into Python (i.e. it is not an external library) and it contains a mode
function:
>>> from statistics import mode
>>> mode([1, 2, 3, 3, 4])
3