Find the second most repeated word in a string.

In this program, we will take a string as input and find the second most repeated word in a given string.

Steps to solve the program
  1. Take a string as input and create an empty dictionary.
  2. Use for loop to iterate over each word of the string.
  3. Add a word as the key and its occurrences in a string as the value in the dictionary.
  4. Use sorted() and lambda function to sort the dictionary by values.
  5. Print the second most repeated word in a string.
				
					#Input string
string = "ab bc ac ab bd ac nk hj ac"
dictionary = dict()

for char in string.split(" "):
    if char != " ":
        dictionary[char] = string.count(char)

counts_ = sorted(dictionary.items(), key=lambda val: val[1])
#Printing output
print(counts_[-2])
				
			

Output :

				
					('ab', 2)
				
			

find the first repeated word in a given string. 

remove spaces from a given string.

Leave a Comment