0

I have an input list, say x = [1,1,2,1,4,3,5,3,3] and I want to find the mode using Python 2.6.

Google so far gives me only answers such as Counter, statistics and mode() which all work for Python 2.7 and higher, but not 2.6.

My question now is: would anyone know how to easily calculate the mode(s) of such a list without programming the whole function itself?

Fraukje
  • 673
  • 3
  • 20
  • *without programming the whole function itself?* <--- It wouldn't be so big, just a simple for loop and an `if...else` with a dict. – Remi Guan Dec 23 '15 at 14:38
  • Yeah you are right Kevin! I'm just curious if there are built-in functions – Fraukje Dec 23 '15 at 14:46

4 Answers4

2

If you're doing statistical work, you might already have scipy installed. If that's the case, you can use scipy.stats.mode.

If not, you'll need to write your own function or get one from some other 3rd party library since there isn't one in the standard library in python2.6.

Also, apparently, scipy.stats.mode only depends on numpy, so you could just copy the source for that if you have numpy but don't want to download scipy . . .

Community
  • 1
  • 1
mgilson
  • 300,191
  • 65
  • 633
  • 696
1
x = [1,1,2,1,4,3,5,3,3]
print [i for i in set(x) if x.count(i) == max(map(x.count, x))]

result:

[1, 3]

if you need to reuse, maybe a lambda function:

mode = lambda x: [i for i in set(x) if x.count(i) == max(map(x.count, x))]
x = [1,1,2,1,4,3,5,3,3]
print mode(x)
Mukund M K
  • 81
  • 4
0

If you're averse to writing your own function, check PyPI for possible modules. This one seems to be a likely candidate, but there may be others:

https://pypi.python.org/pypi/Counter/1.0.0

Lav
  • 2,204
  • 12
  • 23
0
x= [1,2,3,1,2,4,5]
y = set(x)
countDict = {}
for item in y:
    countDict[item] = x.count(item)

result:

{1: 2, 2: 2, 3: 1, 4: 1, 5: 1}