Skip to content

Instantly share code, notes, and snippets.

@laszlokiraly
Created October 22, 2016 12:13
Show Gist options
  • Save laszlokiraly/232854aa89551e11f1bea464dd416f3b to your computer and use it in GitHub Desktop.
Save laszlokiraly/232854aa89551e11f1bea464dd416f3b to your computer and use it in GitHub Desktop.
def count_words(s, n):
"""Return the n most frequently occuring words in s."""
wordlist = s.split(" ")
# TODO: Count the number of occurences of each word in s
worddict = {}
for word in wordlist:
if word in worddict: worddict[word] += 1
else: worddict[word] = 1
# TODO: Sort the occurences in descending order (alphabetically in case of ties)
# TODO: Return the top n words as a list of tuples (<word>, <count>)
return sorted(sorted(worddict.items()), key=lambda x: -x[1])[:n]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment