Modal value of an array

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Mar 28 23:56:39 EDT 2007


"datta.abhirup at gmail.com" <datta.abhirup at gmail.com> 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



More information about the Python-list mailing list