Open In App

Second most repeated word in a sequence in Python

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence. (Considering no two words are the second most repeated, there will be always a single word).

Examples: 

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

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

This problem has existing solution please refer Second most repeated word in a sequence link. We can solve this problem quickly in Python using Counter(iterator) method. 
Approach is very simple – 

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

Implementation

Python3




# Python code to print Second most repeated
# word in a sequence in Python
from collections import Counter
 
 
def secondFrequent(input):
 
    # Convert given list into dictionary
    # it's output will be like {'ccc':1,'aaa':3,'bbb':2}
    dict = Counter(input)
 
    # Get the list of all values and sort it in ascending order
    value = sorted(dict.values(), reverse=True)
 
    # Pick second largest element
    secondLarge = value[1]
 
    # Traverse dictionary and print key whose
    # value is equal to second large element
    for (key, val) in dict.items():
        if val == secondLarge:
            print(key)
            return
 
 
# Driver program
if __name__ == "__main__":
    input = ['aaa', 'bbb', 'ccc', 'bbb', 'aaa', 'aaa']
    secondFrequent(input)


Output

bbb

Time complexity: O(nlogn) where n is the length of the input list
Auxiliary space: O(n) where n is the length of the input list

Alternate Implementation : 

Python3




# returns the second most repeated word
from collections import Counter
class Solution:
    def secFrequent(self, arr, n):
        all_freq = dict(Counter(arr))
        store = []
        for w in sorted(all_freq, key=all_freq.get):
            # if add key=all_freq.get will sort according to values
            # without key=all_freq.get will sort according to keys
            if w not in store:
                store.append(w)
             
        return store[-2]
# driver code or main function
if __name__ == '__main__':
    # no. of test cases
    t = 1
    for _ in range(t):
        # no of words
        n = 7
        # String of words
        arr = ["cat","mat","cat","mat","cat",'ball',"tall"]
        ob = Solution()
        ans = ob.secFrequent(arr,n)
        print(ans)


Output

mat

Time complexity: O(nlogn)
Auxiliary space: O(n)

Approach#3: using dictionary

We can use a dictionary to count the frequency of each word in the sequence. Then, we can find the second most repeated word by iterating over the dictionary and keeping track of the maximum and second maximum frequency.

Steps that were to follow the above approach:

  • Create an empty dictionary to count the frequency of each word in the sequence.
  • Iterate over each word in the sequence and update its frequency in the dictionary.
  • Initialize the maximum and second maximum frequency to 0 and -1, respectively.
  • Iterate over the items in the dictionary and update the maximum and second maximum frequency if necessary.
  • Return the word corresponding to the second maximum frequency.

Python3




def second_most_repeated_word(sequence):
    word_count = {}
    for word in sequence:
        if word in word_count:
            word_count[word] += 1
        else:
            word_count[word] = 1
    max_freq = 0
    second_max_freq = -1
    for word, freq in word_count.items():
        if freq > max_freq:
            second_max_freq = max_freq
            max_freq = freq
        elif freq > second_max_freq and freq < max_freq:
            second_max_freq = freq
    for word, freq in word_count.items():
        if freq == second_max_freq:
            return word
 
# Example usage
sequence = ["aaa", "bbb", "ccc", "bbb", "aaa", "aaa"]
print(second_most_repeated_word(sequence)) # Output: bbb


Output

bbb

Time complexity: O(n), where n is the number of words in the sequence. This is due to the iteration over each word in the sequence and the items in the dictionary.

Space complexity: O(n), where n is the number of words in the sequence. This is due to the storage of the dictionary.



Similar Reads

Second most repeated word in a sequence
Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence.(Considering no two words are the second most repeated, there will be always a single word). Examples: Input : {"aaa", "bbb", "ccc", "bbb", "aaa", "aaa"}Output : bbbInput : {"geeks", "for", "geeks", "for", "geeks", "aaa"}Output :
8 min read
Find the most repeated word in a text file
Python provides inbuilt functions for creating, writing, and reading files. Two types of files can be handled in python, normal text files, and binary files (written in binary language,0s and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\n
2 min read
Most frequent word in first String which is not present in second String
Given two string 'S1' and 'S2', the task is to return the most frequent (which is used the maximum number of times) word from 'S1' that is not present in 'S2'. If more than one word is possible then print lexicographically smallest among them. Examples: Input: S1 = "geeks for geeks is best place to learn", S2 = "bad place" Output: geeks "geeks" is
7 min read
Find the first repeated word in a string in Python using Dictionary
Prerequisite : Dictionary data structure Given a string, Find the 1st repeated word in a string. Examples: Input : "Ravi had been saying that he had been there" Output : had Input : "Ravi had been saying that" Output : No Repetition Input : "he had had he" Output : he We have existing solution for this problem please refer Find the first repeated w
4 min read
Python | Largest, Smallest, Second Largest, Second Smallest in a List
Since, unlike other programming languages, Python does not have arrays, instead, it has list. Using lists is more easy and comfortable to work with in comparison to arrays. Moreover, the vast inbuilt functions of Python, make the task easier. So using these techniques, let's try to find the various ranges of the number in a given list. Examples: In
5 min read
Find the first repeated word in a string
Given a string, Find the 1st repeated word in a string. Examples: Input: "Ravi had been saying that he had been there"Output: hadInput: "Ravi had been saying that"Output: No Repetition Input: "he had had he" he question source: https://www.geeksforgeeks.org/goldman-sachs-interview-experience-set-29-internship/ Recommended: Please solve it on “PRACT
15+ min read
Python program to read file word by word
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file word by word. Read file word by wordIn this article, we will look at how to read a text file and split it into single words using Python. Here are a few examples of reading a file word by word in Python for a bette
2 min read
Python Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”
4 min read
Maximize count of 1s in an array by repeated division of array elements by 2 at most K times
Given an array arr[] of size N and an integer K, the task to find the maximum number of array elements that can be reduced to 1 by repeatedly dividing any element by 2 at most K times. Note: For odd array elements, take its ceil value of division. Examples: Input: arr[] = {5, 8, 4, 7}, K = 5Output: 2Explanation:5 needs 3 operations(5?3?2?1).8 needs
6 min read
Find the lexicographically smallest sequence which can be formed by re-arranging elements of second array
Given two arrays A and B of N integers. Reorder the elements of B in itself in such a way that the sequence formed by (A[i] + B[i]) % N after re-ordering is the smallest lexicographically. The task is to print the lexicographically smallest sequence possible. Note: The array elements are in range [0, n).Examples: Input: a[] = {0, 1, 2, 1}, b[] = {3
11 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg