Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print all words occurring in a sentence exactly K times
When you need to print all words occurring in a sentence exactly K times, you can use Python's string methods like split(), count(), and remove(). This approach counts word frequency and displays words that match the specified frequency.
Example
Below is a demonstration of finding words with exact frequency ?
def key_freq_words(my_string, K):
my_list = list(my_string.split(" "))
for i in my_list:
if my_list.count(i) == K:
print(i)
my_list.remove(i)
my_string = "hi there how are you, how are u"
K = 2
print("The string is :")
print(my_string)
print("The repeated words with frequency", K, "are :")
key_freq_words(my_string, K)
The string is : hi there how are you, how are u The repeated words with frequency 2 are : how are
How It Works
The algorithm follows these steps ?
The
key_freq_wordsfunction takes a string and frequency K as parametersThe string is split by spaces using
split(" ")to create a word listFor each word in the list,
count()checks its frequencyIf the word appears exactly K times, it's printed and removed from the list
Removing printed words prevents duplicate output for the same word
Improved Approach Using Collections
A more efficient approach uses Counter from collections module ?
from collections import Counter
def find_words_with_frequency(sentence, k):
words = sentence.split()
word_count = Counter(words)
result = [word for word, count in word_count.items() if count == k]
return result
sentence = "hi there how are you, how are u"
k = 2
print("The string is:", sentence)
print(f"Words appearing exactly {k} times:")
words = find_words_with_frequency(sentence, k)
for word in words:
print(word)
The string is: hi there how are you, how are u Words appearing exactly 2 times: how are
Comparison
| Method | Time Complexity | Advantages | Disadvantages |
|---|---|---|---|
| Basic approach | O(n²) | Simple to understand | Inefficient for large texts |
| Counter approach | O(n) | More efficient, cleaner code | Requires importing collections |
Conclusion
Use the basic approach with count() and remove() for simple cases. For better performance with larger datasets, use Counter from collections module to efficiently count word frequencies.
