Exercise 88
Write a Python script that takes as input a string s and which returns the first repeated word within the string s. Example: if s = "python programming language, is the most popular programming language", this algorithm returns the word: 'programming'
Solution
""" Python function to achieve this task using a dictionary to keep track of the words encountered so far """ def first_repeated_word(s): # Split the string into words words = s.split() # Create an empty dictionary to store word frequencies word_freq = {} # Iterate through each word in the string for word in words: # If the word is already in the dictionary, return it if word in word_freq: return word # Otherwise, add the word to the dictionary with a frequency of 1 else: word_freq[word] = 1 # If no repeated word is found, return None return None # Example usage s = "python programming language, is the most popular programming language" print("The first repeated word is : " , first_repeated_word(s)) # Output: programming # output: The first repeated word is : programming
Younes Derfoufi
CRMEF OUJDA
[…] Exercise 88 * || Solution […]