On Mar 30, 2:58 am, [EMAIL PROTECTED] (Alex Martelli) wrote: > 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
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. -- http://mail.python.org/mailman/listinfo/python-list