Python Practice › String Programs › Program 69

Second most repeated word

EasyString Programs · 69 of 106

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

Advertisement
Input
"ab bc ac ab bd ac nk hj ac"
Output
('ab', 2)

Approach

  1. Counter.most_common() returns words sorted by count.

Solution

Python
from collections import Counterprint(Counter("ab bc ac ab bd ac nk hj ac".split()).most_common(2)[1])
Output
('ab', 2)

Line by line

Line 2

most_common(2) gives the top two pairs; index 1 is the second.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs