Modal value of an array

Paddy paddy3118 at googlemail.com
Fri Mar 30 00:44:56 CEST 2007


On Mar 29, 8:49 am, a... at mac.com (Alex Martelli) wrote:
> Ben Finney <bignose+hates-s... at benfinney.id.au> wrote:
>
>    ...
>
> > 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'
>
> A bit more directly:
>
> >>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"]
> >>> max(foo, key=foo.count)
>
> 'spam'
>
> Alex

This doesn't call foo.count for duplicate entries by keeping a cache

>>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"]
>>> def cachecount(x, cache={}):
... 	return cache.setdefault(x, foo.count(x))
...
>>> max(foo, key=cachecount)
'spam'
>>> cachecount.func_defaults
({'eggs': 2, 'beans': 1, 'spam': 4},)
>>>

- Paddy.




More information about the Python-list mailing list