3 ms·
most_common(n) takes an optional argument, which makes a difference. With no arguments, you're just sorting the list, but when you just want the first N, you d
by bdarnell 15y ago
most_common(n) takes an optional argument, which makes a difference. With no arguments, you're just sorting the list, but when you just want the first N, you don't have to sort the entire list first. However, the partial-sorting optimizations are generally not symmetric, so supporting both most and least common would imply that either one direction is slower than the other, or the implementation is not as efficient as it could be for the case where only one direction is important. Only supporting most_common(n) makes it clear which case is optimized for.
- d0mine 15y agodef least_common(c, n=None): key = operator.itemgetter(1) if n is None: return sorted(c.items(), key=key) return heapq.nsmallest(n, c.items(), key=key) It has the same efficiency as Counter.most_common().
- beaumartinez 15y agoIn this case (Python's collections.Counter[1]), the argument doesn't do what you suggest: you don't return the most common out of the first n items, you return the n most common items. I don't know anything of the specifics of partial sorting but if the argument did what you suggest I'd guess the code would have a line like: # Deal only with the first n items. items = items[:n] As it would make the code much simpler (quoting from The Zen Of Python, "special cases aren't special enough to break the rules"—we don't need a partial sort). [1] http://docs.python.org/library/collections.html#counter-objects http://docs.python.org/library/collections.html#counter-obje...