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 `

Shop

Learn programming in R: courses

\$

Best Python online courses for 2022

\$

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

\$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

NUMPYNUMPY

How to specify multiple return types using type-hints

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

NUMPYNUMPY

glob exclude pattern

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

NUMPYNUMPY

Python CSV error: line contains NULL byte

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries