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
- Take a string as input and create an empty dictionary.
- Use for loop to iterate over each word of the string.
- Add a word as the key and its occurrences in a string as the value in the dictionary.
- Use sorted() and lambda function to sort the dictionary by values.
- 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)