0

I have been trying to figure out how to find the mode of a list WITHOUT using sorting functions nor importing any modules for quite awhile now... Here's what I have so far:

d = {}
def mode():
    for i in mode:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    return

How do I find the output such as the following:

print(mode([1, 5, 6, 1, 1, 2]))
[1]
print(mode([5, 6, 7, 8, 9]))
[5, 6, 7, 8, 9]

Thanks a bunch!

DaveNOTDavid
  • 1,753
  • 5
  • 19
  • 37

2 Answers2

0

You need to count the occurrences in your dict and extract the max based on the value returning the list itself if there is no mode.

def mode(l):
     d= {}
    for i in l:
        d.setdefault(i, 0)
        d[i] += 1
    mx = max(d,key=d.get)
    return d[mx] if d[mx] > 1 else l 
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
-1

Use a dictionary with the value as the key and a count as value. If you're using Python 3, this is the Counter data type.

When you've tallied all the entries, find the max of the values. Make a list comprehension of all elements with that value.

Prune
  • 76,765
  • 14
  • 60
  • 81
  • 1
    OP said no imports, so `collections.Counter` is out. Relatedly, `Counter` was added in 2.7, so you don't need Python 3 to have access to it. – ShadowRanger Sep 28 '15 at 23:13