File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ def most_frequent_word (str ):
2+ """ Find k most frequent words in a string of words, and print them in space-separated alphabetical order.
3+
4+ >>> most_frequent_word('hello my name is hello joanne')
5+ hello
6+
7+ >>> most_frequent_word('hello my name is hello joanne is')
8+ hello is
9+
10+ >>> most_frequent_word('hello my name is joanne')
11+ hello is joanne my name
12+ """
13+
14+ # time: O(n log n)
15+ # space: O(n)
16+
17+ words = {}
18+ list_of_words = str .split ()
19+
20+ for word in list_of_words :
21+ words [word ] = words .get (word , 0 ) + 1
22+
23+ most_frequent_words = []
24+
25+ max_value = max (words .values ())
26+
27+ for word , value in words .iteritems ():
28+ if value == max_value :
29+ most_frequent_words .append (word )
30+
31+ for word in sorted (most_frequent_words ):
32+ print word ,
33+
34+
35+
36+
37+
38+
39+
40+ if __name__ == '__main__' :
41+ import doctest
42+ results = doctest .testmod ()
43+ if not results .failed :
44+ print 'All tests passed!'
You can’t perform that action at this time.
0 commit comments