From 9a894ebc521a8b09613737905608dbfd8be5faf4 Mon Sep 17 00:00:00 2001 From: Sarath Kaul Date: Sun, 17 Nov 2019 17:27:26 +0530 Subject: [PATCH] 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 --- strings/word_occurence.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 strings/word_occurence.py diff --git a/strings/word_occurence.py b/strings/word_occurence.py new file mode 100644 index 000000000..c4eb923d6 --- /dev/null +++ b/strings/word_occurence.py @@ -0,0 +1,23 @@ +# Created by sarathkaul on 17/11/19 +from collections import defaultdict + + +def word_occurence(sentence: str) -> dict: + """ + >>> from collections import Counter + >>> SENTENCE = "a b A b c b d b d e f e g e h e i e j e 0" + >>> occurence_dict = word_occurence(SENTENCE) + >>> all(occurence_dict[word] == count for word, count + ... in Counter(SENTENCE.split()).items()) + True + """ + occurence = defaultdict(int) + # Creating a dictionary containing count of each word + for word in sentence.split(" "): + occurence[word] += 1 + return occurence + + +if __name__ == "__main__": + for word, count in word_occurence("INPUT STRING").items(): + print(f"{word}: {count}")