Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Well, 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.


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.


In 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-obje...


  def 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().




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: