Skip to content

Commit 4a65f2e

Browse files
committed
Create most_frequent_word.py
1 parent 59d7089 commit 4a65f2e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

most_frequent_word.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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!'

0 commit comments

Comments
 (0)