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_words function takes a string and frequency K as parameters

  • The string is split by spaces using split(" ") to create a word list

  • For each word in the list, count() checks its frequency

  • If 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.

Updated on: 2026-03-26T02:04:29+05:30

470 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements