CBSE Class 12 Computer Science Question 35 of 57

Review of Python Basics — Question 35

Back to all questions
35
Question

Question 30

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

Solution
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
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