3

Basically I just need to figure out how to produce modes (numbers occurring most frequently) from a list in Python, whether or not that list has multiple modes?

Something like this:

def print_mode (thelist):
  counts = {}
  for item in thelist:
    counts [item] = counts.get (item, 0) + 1
  maxcount = 0
  maxitem = None
  for k, v in counts.items ():
    if v > maxcount:
      maxitem = k
      maxcount = v
  if maxcount == 1:
    print "All values only appear once"
  if counts.values().count (maxcount) > 1:
    print "List has multiple modes"
  else:
    print "Mode of list:", maxitem

But instead of returning strings in the "All values only appear once," or "list has multiple modes," I would want it to return the actual integers that it's referencing?

hayleyelisa
  • 359
  • 4
  • 5
  • 15

3 Answers3

13

Make a Counter, then pick off the most common elements:

from collections import Counter
from itertools import groupby

l = [1,2,3,3,3,4,4,4,5,5,6,6,6]

# group most_common output by frequency
freqs = groupby(Counter(l).most_common(), lambda x:x[1])
# pick off the first group (highest frequency)
print([val for val,count in next(freqs)[1]])
# prints [3, 4, 6]
nneonneo
  • 171,345
  • 36
  • 312
  • 383
1
def mode(arr):

if len(arr) == 0:
    return []

frequencies = {}

for num in arr:
    frequencies[num] = frequencies.get(num,0) + 1

mode = max([value for value in frequencies.values()])

modes = []

for key in frequencies.keys():
    if frequencies[key] == mode:
        modes.append(key)

return modes

This code can tackle with any list. Make sure, elements of the list are numbers.

grad f
  • 47
  • 5
0

new in python 3.8's statistics module there is a function for that:

import statistics as s
print("mode(s): ",s.multimode([1,1,2,2]))

output: mode(s): [1, 2]

user_number153
  • 492
  • 4
  • 7