Most frequently occuring n words in a string
<p>I have a problem with the following problem:</p>

<p><strong>Problem</strong>:</p>

<p>Implement a function count_words() in Python that takes as input a string s and a number n, and returns the n most frequently-occuring words in s. The return value should be a list of tuples - the top n words paired with their respective counts [(, ), (, ), ...], sorted in descending count order.</p>

<p>You can assume that all input will be in lowercase and that there will be no punctuations or other characters (only letters and single separating spaces). In case of a tie (equal count), order the tied words alphabetically.</p>

<p>E.g.:</p>

<p>print count_words("betty bought a bit of butter but the butter was bitter",3)
Output:</p>

<p>[('butter', 2), ('a', 1), ('betty', 1)]</p>

<p><strong>This is my solution:</strong></p>

<pre><code>    """Count words."""

from operator import itemgetter
from collections import Counter

def count_words(s, n):
    """Return the n most frequently occuring words in s."""

    # TODO: Count the number of occurences of each word in s
    words = s.split(" ");
    words = Counter(words)
    # TODO: Sort the occurences in descending order (alphabetically in case of ties)
    print(words)
    # TODO: Return the top n words as a list of tuples (&lt;word&gt;, &lt;count&gt;)
    top_n = words.most_common(n)
    return top_n

def test_run()

    """Test count_words() with some inputs."""
    print(count_words("cat bat mat cat bat cat", 3))
    print(count_words("betty bought a bit of butter but the butter was bitter", 3))


if __name__ == '__main__':
    test_run()
</code></pre>

<p>The problem is that elements with equal counts are ordered arbitrarily, how can i order that elements by alphabetical order ??</p>

<p>The python function <code>sorted</code> is <a href="http://stackoverflow.com/a/1915418/1112586">stable</a>, which means in case of a tie, the tied items will be in the same order. Because of this, you can sort first on the strings to get them in order:</p>

<pre><code>alphabetical_sort = sorted(words.items(), key=lambda x: x[0])
</code></pre>

<p>and then on the counts:</p>

<pre><code>final_sort = sorted(alphabetical_sort, key=lambda x: x[1], reverse=True)
</code></pre>

<p><strong>Edit:</strong> Didn't see Moses' better answer. Of course, the less sorts the better.</p>

python