From 25388212f9d161c0cef8dc031f98025d5bba8061 Mon Sep 17 00:00:00 2001 From: Milad Khoshdel Date: Fri, 4 Sep 2026 21:45:10 +0330 Subject: [PATCH 1/2] refactor: simplify word_occurrence using dict --- strings/word_occurrence.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/strings/word_occurrence.py b/strings/word_occurrence.py index 5a18ebf771e4..44e9163679c1 100644 --- a/strings/word_occurrence.py +++ b/strings/word_occurrence.py @@ -1,23 +1,21 @@ # Created by sarathkaul on 17/11/19 # Modified by Arkadip Bhattacharya(@darkmatter18) on 20/04/2020 -from collections import defaultdict - -def word_occurrence(sentence: str) -> dict: +def word_occurrence(sentence: str) -> dict[str, int]: """ >>> 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_occurrence(SENTENCE) - >>> all(occurence_dict[word] == count for word, count + >>> occurrence_dict = word_occurrence(SENTENCE) + >>> all(occurrence_dict[word] == count for word, count ... in Counter(SENTENCE.split()).items()) True >>> dict(word_occurrence("Two spaces")) {'Two': 1, 'spaces': 1} """ - occurrence: defaultdict[str, int] = defaultdict(int) - # Creating a dictionary containing count of each word + occurrence: dict[str, int] = {} + for word in sentence.split(): - occurrence[word] += 1 + occurrence[word] = occurrence.get(word, 0) + 1 return occurrence From 5bccc578341bebd652e4d06ed3c5a90880c5733b Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 4 Sep 2026 18:28:22 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- strings/word_occurrence.py | 1 + 1 file changed, 1 insertion(+) diff --git a/strings/word_occurrence.py b/strings/word_occurrence.py index 44e9163679c1..420aeba74df7 100644 --- a/strings/word_occurrence.py +++ b/strings/word_occurrence.py @@ -1,6 +1,7 @@ # Created by sarathkaul on 17/11/19 # Modified by Arkadip Bhattacharya(@darkmatter18) on 20/04/2020 + def word_occurrence(sentence: str) -> dict[str, int]: """ >>> from collections import Counter