Word Parser

Run Settings
LanguagePython
Language Version
Run Command
def count_words(s, n): """Return the n most frequently occuring words in s.""" tuple_list = [] s = s+' ' # TODO: Count the number of occurences of each word in s while s.find(' ')!=-1: word = s[0:s.find(' ')] s = s[s.find(' ')+1:] if word not in dict(tuple_list): tuple_list.append((word, 1)) else: tuple_list = [(e, cont+1) if e == word else (e, cont) for (e, cont) in tuple_list] # TODO: Sort the occurences in descending order (alphabetically in case of ties) sorted_list = sorted(tuple_list, key=lambda x: x[0]) sorted_list = sorted(sorted_list, key=lambda x: x[1], reverse=True) # TODO: Return the top n words as a list of tuples (<word>, <count>) top_n = sorted_list[0:n] return top_n 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)
Editor Settings
Theme
Key bindings
Full width
Lines