Skip to content

Instantly share code, notes, and snippets.

@romainmet
Last active May 21, 2025 15:30
Show Gist options
  • Save romainmet/c43faa9b55c6b7be783a to your computer and use it in GitHub Desktop.
Save romainmet/c43faa9b55c6b7be783a to your computer and use it in GitHub Desktop.
Udacity Assessment Answer - Machine Learning Nanodegree
"""Count words."""
count={}
def count_words(s, n):
"""Return the n most frequently occuring words in s."""
wordlist = s.split()
wordfreq = [wordlist.count(p) for p in wordlist]
zip_l=dict(zip(wordlist,wordfreq))
sort=sorted(zip_l.iteritems(),key=lambda(k,v):(-v,k))
top_n=sort[0: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()
@913897639
Copy link

Screenshot_20250521-175913
Screenshot_20250521-175804
Screenshot_20250521-175726
Screenshot_20250521-175719
Screenshot_20250521-175608
Screenshot_20250521-175531
Screenshot_20250521-175457
Screenshot_20250521-175436
Screenshot_20250521-175420
Uploading Screenshot_20250521-175354.jpg…

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment