I need help writing a function findMode(aList) that accepts a list of items as a parameter, and proceeds to find the mode. However, your Python solution must use a dictionary to keep track of the items and their counts as the method of finding the mode (not parallel lists).

Here is the code that i have already tried:

def findMode(aList):
    aList.sort()
    position = 0
    largestCount = 0
    listLength = len(aList)
    while(position <= listLength):
        count = aList.count(aList[position])
        if(count > largestCount):
            largestCount = count
            valuePosition = aList[position]
        position += count
    return aList[valuePosition]

Here are some examples of the desired outcome:

>>> findMode([4,3,4,3,2,1,4,5,3,3,4,5,1,4,1,4,5])
[4]
>>> findMode(["horse ", "cat ", "dog ", "turtle ","horse ", "cat ", "dog ", "turtle "])
['horse ', 'cat ', 'dog ', 'turtle ']

3 Answers

4
Joan Lara Ganau On

This should do the trick:

from collections import Counter

def findMode(aList):
    counter = Counter(aList)
    max_count = max(counter.values())
    return [item for item, count in counter.items() if count == max_count]
0
Paindemie On
def findMode(aList):
  dic_freq = {}
  for element in aList:
    if element not in aList.keys():
      dic_freq[element] = 1
    else:
      dic_freq[element] += 1

  mode = [el for el in dic_freq.keys() if dic_freq[el] == max(dic_freq.values())]
  return mode

You can do it faster without dictionary but it works that way

0
prashant rana On
from collections import defaultdict
def findMode(aList):
    dic = defaultdict(int)
    for i in aList:
        dic[i]+=1
    mv = max(dic.values())
    return [i for i in dic if dic[i]==mv]

findMode([4,3,4,3,2,1,4,5,3,3,4,5,1,4,1,4,5])
# output [4]

findMode(["horse ", "cat ", "dog ", "turtle ","horse ", "cat ", "dog ", "turtle "])
# output ['horse ', 'cat ', 'dog ', 'turtle ']