Change language

Second most repeated word in a sequence in Python

| |

Examples:

 Input: {"aaa", "bbb", "ccc", "bbb", "aaa", "aaa"} Output: bbb Input: {"geeks", " for "," geeks "," for "," geeks "," aaa "} Output: for 

This problem has an existing solution, please refer to second most repeated word in link Counter (iterator) method.

The approach is very simple —

  1. Create a dictionary using the Counter (iterator) method which contains words as keys and their frequency as values.
  2. Now get a list of all the values ​​in the dictionary and sort it in descending order. Select the second item from the sorted list because it will be the second largest.
  3. Now go through the dictionary again and print the key whose value is equal to the second largest item.

# Python print code Second most repetitive
# word in sequence in Python

from collections import Counter

 

def secondFrequent ( input ):

  

# Convert this list to a dictionary

  # this will look like {& # 39; ccc & # 39 ;: 1, & # 39; aaa & # 39 ;: 3, & # 39; bbb & # 39 ;: 2}

dict = Counter ( input )

 

# Get list all values ​​and sort it in ascending order

value = sorted ( dict . values ​​(), reverse = True )

 

# Select the second largest item

secondLarge = value [ 1 ]

 

# Go through the dictionary and type the key of which

# the value is equal to the second big item

for (key, val) in dict . iteritems ():

if val = = secondLarge:

  print key

  return

  
# Driver program

if __ name__ = = "__ main__" :

input = [ ’aaa’ , ’ bbb’ , ’ccc’ , ’ bbb ’ , ’ aaa’ , ’aaa’ ]

secondFrequent ( input )

Output:

 bbb 

Second most repeated word in a sequence in Python Counters: Questions

Second most repeated word in a sequence in Python Python functions: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method