Find the first repeated word in a string in Python using Dictionary

PythonServer Side ProgrammingProgramming

In a given sentence there may be a word which get repeated before the sentence ends. In this python program, we are going to catch such word which is repeated in sentence. Below is the logical steps we are going to follow to get this result.

  • Splits the given string into words separated by space.
  • Then we convert these words into Dictionary using collections
  • Traverse this list of words and check which first word has the frequency > 1

Program - Find the Repeated Word

In the below program we use the counter method from the collections package to keep a count of the words.

Example

 Live Demo

from collections import Counter
def Repeat_word(load):
   word = load.split(' ')
   dict = Counter(word)
   for value in word:
      if dict[value]>1:
         print (value)
            return
if __name__ == "__main__":
   input = 'In good time in bad time friends are friends'
   Repeat_word(input)

Running the above code gives us the following result −

Output

time
raja
Published on 19-Dec-2019 16:56:52
Advertisements