Word Frequency — LeetCode 192 Python Solution
MediumShell
- Problem
- #192
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Write a bash script to calculate the frequency of each word in a text file words.txt. For simplicity sake, you may assume: words.txt contains only lowercase characters and space ' ' characters.
Example
the day is sunny the the the sunny is is
Python solution
Python
from collections import Counter
def word_frequency(path: str = "words.txt") -> None:
with open(path, "r", encoding="utf-8") as f:
words = f.read().split()
counts = Counter(words)
for word, cnt in sorted(counts.items(), key=lambda x: (-x[1], x[0])):
print(f"{word} {cnt}")Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) to O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 192. Word Frequency?
- LeetCode 192. Word Frequency is rated Medium on LeetCode.
- What topics does LeetCode 192. Word Frequency cover?
- LeetCode 192. Word Frequency is tagged Shell on LeetCode.