KnowledgeBoat Logo

Computer Science

Write a Python program to find the second most repeated word in a given string.

Python

Python String Manipulation

1 Like

Answer

input_string = input("Enter the string: ")
words = input_string.split()

word_counts = {}
for word in words:
    if word in word_counts:
        word_counts[word] += 1
    else:
        word_counts[word] = 1

max_count = 0
second_max_count = 0
most_repeated_word = None
second_most_repeated_word = None

for word, count in word_counts.items():
    if count > max_count:
        second_max_count = max_count
        max_count = count
        second_most_repeated_word = most_repeated_word
        most_repeated_word = word
    elif count > second_max_count:
        second_max_count = count
        second_most_repeated_word = word

print(second_most_repeated_word)

Output

Enter the string: apple banana cherry banana cherry cherry
banana

Answered By

1 Like


Related Questions