Skip to content

Instantly share code, notes, and snippets.

@du2x
Last active April 5, 2016 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save du2x/f2da4bbb04dcb05032973b98411006bb to your computer and use it in GitHub Desktop.
Save du2x/f2da4bbb04dcb05032973b98411006bb to your computer and use it in GitHub Desktop.
def count_words(s, n):
"""Return the n most frequently occuring words in s ordered by number
of ocurrences and alfabetically."""
ws = {}
for w in s.split():
if w in ws.keys():
ws[w]+=1
else:
ws[w]=1
sorted_ws = sorted(ws.items(), key=lambda x: (-x[1], x[0]))
return sorted_ws[0:n]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment