Paddy <[EMAIL PROTECTED]> 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 -- http://mail.python.org/mailman/listinfo/python-list