Modal value of an array

Alex Martelli aleax at mac.com
Thu Mar 29 21:58:45 EDT 2007


Paddy <paddy3118 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



More information about the Python-list mailing list