[Tutor] get the mode of a list

Jacob S. keridee at jayco.net
Fri Oct 22 01:28:38 CEST 2004


Hi, I hope I don't spoil a learning experience by giving you this, but I
will anyway. I want you to look it over and see that it works and why it
works so as not to spoil that learning experience ;-)


def getmode(li):
    li.sort()
    numbers = {}
    for x in li:
        num = li.count(x)
        numbers[x] = num
    highest = max(numbers.values())
    n = []
    for m in numbers.keys():
        if numbers[m] == highest:
            n.append(m)
    return n

If you want it to tell you specifically when all of the list members are
modes, then you can check for that by seeing if the list before is equal to
the return list. If you want it to return an integer instead of a list, you
might try print statements or int(). Have fun.

Sincerely,
Jacob Schmidt



More information about the Tutor mailing list