Well, the first problem is that yes, you are returning the value in the frequences rather than the key. This means that you get the score of the mode, not the mode itself. Usually, to get the mode, you should use the key keyword argument for max, for example:
>>> max(frequencies, key=counts.get())
But in 2.4, which does not exist! Here's an approach that I believe will work in version 2.4:
>>> import random >>> l = [random.randrange(0, 5) for _ in range(50)] >>> frequencies = {} >>> for i in l: ... frequencies[i] = frequencies.get(i, 0) + 1 ... >>> frequencies {0: 11, 1: 13, 2: 8, 3: 8, 4: 10} >>> mode = max((v, k) for k, v in frequencies.iteritems())[1] >>> mode 1 >>> max_freq = max(frequencies.itervalues()) >>> modes = [k for k, v in frequencies.iteritems() if v == max_freq] >>> modes [1]
I prefer the decorate-sort-undecorate identifier with the cmp keyword. I think this is more readable. Maybe just me.
source share