-3

I am trying to achieve this without the use of external libraries. If anyone could help me out with this and include a bit of an explanation that would be greatly appreciated.

def mode(list):
     dictionary= {}
    for i in list:
        dictionary.setdefault(i, 0)
        dictionary[i] += 1
    maximum = max(dictionary,key=dictionary.get)
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Lelefel
  • 7
  • 3

1 Answers1

2

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
Samwise
  • 68,105
  • 3
  • 30
  • 44