Open In App

Python – Consecutive elements maximum frequencies

Last Updated : 17 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python lists we can have a problem in which we need to extract the maximum frequencies of consecutive elements. This kind of problem can occur as application in many domains such as day-day programming and competitive programming. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [7, 6, 7, 7] Output : {7: 2, 6: 1} Input : test_list = [7, 7, 7] Output : {7: 3}

Method #1 : Using loop + groupby() The combination of above functions can be used to perform this task. In this, we group all the consecutive elements and then generate the dictionary of maximum frequencies using dictionary keys comparison with current maximum. 

Python3




# Python3 code to demonstrate working of
# Consecutive elements maximum frequencies
# Using loop + groupby()
from itertools import groupby
 
# initializing list
test_list = [5, 6, 7, 7, 6, 6, 5, 7]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Consecutive elements maximum frequencies
# Using loop + groupby()
res = {}
for key, val in groupby(test_list):
    sub = sum(1 for _ in val)
    if res.get(key, float('-inf')) < sub:
        res[key] = sub
 
# printing result
print("The maximum frequencies : " + str(res))


Output : 

The original list is : [5, 6, 7, 7, 6, 6, 5, 7]
The maximum frequencies : {5: 1, 6: 2, 7: 2}

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. loop + groupby() performs n*n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list

  Method #2 : Using max() + list comprehension + set() + groupby() The combination of above functions can be used to solve this particular problem. In this, we use list comprehension to perform comparisons and maximum element is found using max(). 

Python3




# Python3 code to demonstrate working of
# Consecutive elements maximum frequencies
# Using max() + list comprehension + set() + groupby()
from itertools import groupby
 
# initializing list
test_list = [5, 6, 7, 7, 6, 6, 5, 7]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Consecutive elements maximum frequencies
# Using max() + list comprehension + set() + groupby()
temp = list(set(test_list))
res = [{ele : max([len(list(val)) for key, val in groupby(test_list)
                                  if ele == key])} for ele in temp]
 
# printing result
print("The maximum frequencies : " + str(res))


Output : 

The original list is : [5, 6, 7, 7, 6, 6, 5, 7]
The maximum frequencies : [{5: 1}, {6: 2}, {7: 2}]

Method #3 : Using dictionary+ nested while

Approach

Initialize an empty dictionary to store the frequency count of consecutive elements. Iterate through the list from index 0 to second last index. If the current element and the next element are equal, increment the frequency count of the current element in the dictionary. Return the dictionary.

Algorithm

1.Initialize an empty dictionary freq_dict.
2. Iterate through the list from index 0 to second last index.
3. If the current element and the next element are equal, increment the frequency count of the current element in the dictionary.
4. Return the dictionary.

Python3




def consecutive_element_frequencies_1(lst):
    freq_dict = {}
    i = 0
    while i < len(lst):
        j = i + 1
        while j < len(lst) and lst[j] == lst[i]:
            j += 1
        freq_dict[lst[i]] = j - i
        i = j
    return freq_dict
 
lst = [7, 6, 7, 7]
print(consecutive_element_frequencies_1(lst))


Output

{7: 2, 6: 1}

Time Complexity: O(n), where n is the length of the input list.
Space Complexity: O(n), where n is the length of the input list.

Approach#4: Using lambda

This approach uses the groupby() function from the itertools module to group the consecutive elements in the list and then counts the length of each group to find the maximum frequency of consecutive elements.

Algorithm

1. Import the groupby() function from the itertools module.
2. Define a lambda function that takes a list as input.
3. Use groupby() to group the consecutive elements in the list.
4. For each group, use len() to find the length of the group and store it in a dictionary with the group key.
5. Return the resulting dictionary.

Python3




from itertools import groupby
 
result = lambda lst: {k: len(list(v)) for k, v in groupby(lst)}
 
test_list = [7, 6, 7, 7]
print(result(test_list))
 
test_list = [7, 7, 7]
print(result(test_list))


Output

{7: 2, 6: 1}
{7: 3}

Time complexity: O(n), where n is the length of the input list. This is because the groupby() function iterates through the list only once.

Auxiliary Space: O(n), where n is the length of the input list. This is because the dictionary that stores the counts of consecutive elements will have at most n key-value pairs. The list created by the list() function in the len() method call has a space complexity of O(k), where k is the length of the longest group. However, since k is bounded by n, the overall space complexity is still O(n).



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads