Skip to content

Commit 9a894eb

Browse files
Sarath Kaulcclauss
Sarath Kaul
authored andcommitted
Word Occurence Script Added (#1576)
* Word Occurence Script Added * Word Occurence Script Updated * Added doctest using collections.Counter https://docs.python.org/3/library/collections.html#collections.Counter
1 parent b838f10 commit 9a894eb

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

strings/word_occurence.py

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Created by sarathkaul on 17/11/19
2+
from collections import defaultdict
3+
4+
5+
def word_occurence(sentence: str) -> dict:
6+
"""
7+
>>> from collections import Counter
8+
>>> SENTENCE = "a b A b c b d b d e f e g e h e i e j e 0"
9+
>>> occurence_dict = word_occurence(SENTENCE)
10+
>>> all(occurence_dict[word] == count for word, count
11+
... in Counter(SENTENCE.split()).items())
12+
True
13+
"""
14+
occurence = defaultdict(int)
15+
# Creating a dictionary containing count of each word
16+
for word in sentence.split(" "):
17+
occurence[word] += 1
18+
return occurence
19+
20+
21+
if __name__ == "__main__":
22+
for word, count in word_occurence("INPUT STRING").items():
23+
print(f"{word}: {count}")

0 commit comments

Comments
 (0)