3 ms·
I love python, I really do, and there is a library for everything you can imagine. So when I see things like this: c.most_common()[:-n:-1] # n least commo
by Kilimanjaro 15y ago
I love python, I really do, and there is a library for everything you can imagine. So when I see things like this:
c.most_common()[:-n:-1] # n least common elements
For the love of ceiling_cat, how hard is it to implement a least_common method?
- deleted 15y ago[deleted]
- beaumartinez 15y agoWell, that's pretty ugly anyway―what's wrong with: reversed(c.most_common()) Although I agree that a least_common function would be more "symmetrical" (don't ask me why c has one and not both), you can create it yourself (and have it not only readable but efficient!) in one line of code.
- bdarnell 15y agomost_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...
- deleted 15y ago[deleted]
- natnat 15y agoNot to pick nits, but this is off by one. If you need the n most common elements, you should use c.most_common()[:-n-1:-1] because the element at c.most_common()[-n] is actually the n-1th most common element.