I am trying to get the sorted output from following program.
"""Count words."""
# TODO: Count the number of occurences of each word in s
# TODO: Sort the occurences in descending order (alphabetically in case of ties)
# TODO: Return the top n words as a list of tuples
from operator import itemgetter
def count_words(s, n):
"""Return the n most frequently occuring words in s."""
t1=[]
t2=[]
temp={}
top_n={}
words=s.split()
for word in words:
if word not in temp:
t1.append(word)
temp[word]=1
else:
temp[word]+=1
top_n=sorted(temp.items(), key=itemgetter(1,0),reverse=True)
print top_n
return
def test_run():
"""Test count_words() with some inputs."""
count_words("cat bat mat cat bat cat", 3)
count_words("betty bought a bit of butter but the butter was bitter", 3)
if __name__ == '__main__':
test_run()
This program output is like:
[('cat', 3), ('bat', 2), ('mat', 1)]
[('butter', 2), ('was', 1), ('the', 1), ('of', 1), ('but', 1), ('bought', 1), ('bitter', 1), ('bit', 1), ('betty', 1), ('a', 1)]
but I need in the form like:
[('cat', 3), ('bat', 2), ('mat', 1)]
[('butter', 2), ('a', 1),('betty', 1),('bit', 1),('bitter', 1) ... rest of them here]
COuld you please let me know the best possible way?
(<word>, <count>)