Find the first repeated word in a string in Python using Dictionary
Prerequisite : Dictionary data structure
Given a string, Find the 1st repeated word in a string.
Examples:
Input : "Ravi had been saying that he had been there" Output : had Input : "Ravi had been saying that" Output : No Repetition Input : "he had had he" Output : he
We have existing solution for this problem please refer Find the first repeated word in a string link. We can solve this problem quickly in python using Dictionary data structure. Approach is simple,
- First split given string separated by space.
- Now convert list of words into dictionary using collections.Counter(iterator) method. Dictionary contains words as key and it’s frequency as value.
- Now traverse list of words again and check which first word has frequency greater than 1.
# Function to Find the first repeated word in a string from collections import Counter def firstRepeat(input): # first split given string separated by space # into words words = input.split(' ') # now convert list of words into dictionary dict = Counter(words) # traverse list of words and check which first word # has frequency > 1 for key in words: if dict[key]>1: print key return # Driver program if __name__ == "__main__": input = 'Ravi had been saying that he had been there' firstRepeat(input) |
chevron_right
filter_none
Output:
had
Recommended Posts:
- Second most repeated word in a sequence in Python
- Find frequency of each word in a string in Python
- Python Dictionary to find mirror characters in a string
- Python | Count occurrences of each word in given text file (Using dictionary)
- Python | Convert string dictionary to dictionary
- Python | Converting list string to dictionary
- Python | Converting String content to dictionary
- Python | Convert dictionary object into string
- Python program to create a dictionary from a string
- Python | Removing Initial word from string
- Python | Convert byteString key:value pair of dictionary to String
- Python | Convert key-value pair comma separated string into dictionary
- Python | Find depth of a dictionary
- Python | Find the closest Key in dictionary
- Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



