Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions strings/word_occurrence.py
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,22 @@
# 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Python's default_dict is in the standard library to accelerate use cases like this one. There is a function call overhead in the proposed solution that does not exist in the current solution.

Create a https://docs.python.org/3/library/timeit.html#timeit.timeit benchmark and compare the two on a big dataset.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the feedback. I’ve kept the existing defaultdict implementation unchanged and moved the type-hint and typo fixes into a separate, focused PR: #15194.

return occurrence


Expand Down