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 —
- Create a dictionary using the Counter (iterator) method which contains words as keys and their frequency as values. Li>
- 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.
- 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’ ] cod e> 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