Modal value of an array

Paddy paddy3118 at googlemail.com
Fri Mar 30 01:53:57 EDT 2007


On Mar 30, 2:58 am, a... at mac.com (Alex Martelli) wrote:
> Paddy <paddy3... at googlemail.com> wrote:
>
>    ...
>
>
>
> > > 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},)
>
> If you're willing to do that much extra coding to save some work (while
> still being O(N squared)), then the further small extra needed to be
> O(N) starts looking good:
>
> counts = collections.defaultdict(int)
> for item in foo: counts[item] += 1
> max(foo, key=counts.get)
>
> Alex

Yeh, My first answer is like that but I had to play around with your
original to try and 'fix' the idea in my head - it might be useful
someday.
:-)

- Paddy.




More information about the Python-list mailing list