"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes: > Hi > > How can I find out the modal value in an array. That is the value > which occurs maximum time in the sequence .. > > e.g. if my array has values like [2,3,2,2,2,4,2,2] definitely the > maximum time 2 occurs in the array. so this function should be able to > return 2 as a result ..
That's not the only case though. What do you expect to be returned for an input of ["eggs", "beans", "beans", "eggs", "spam"] ? Assuming you want *a* mode value, and any one will do (e.g. any of "spam", "eggs" or "beans" is okay), I'd write it this way as a first guess: >>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"] >>> counts = [(foo.count(val), val) for val in set(foo)] >>> counts [(2, 'eggs'), (1, 'beans'), (4, 'spam')] >>> sorted(counts)[-1] (4, 'spam') >>> sorted(counts)[-1][1] 'spam' >>> foo = ["eggs", "beans", "beans", "eggs", "spam"] >>> counts = [(foo.count(val), val) for val in set(foo)] >>> sorted(counts)[-1][1] 'eggs' -- \ "Anger makes dull men witty, but it keeps them poor." -- | `\ Elizabeth Tudor | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list