Created
October 22, 2016 12:13
-
-
Save laszlokiraly/232854aa89551e11f1bea464dd416f3b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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