Open In App

Python | Consecutive characters frequency

Last Updated : 21 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python, we can have a problem in which we need to compute the frequency of consecutive characters till the character changes. This can have applications in many domains. Let us discuss certain ways in which this task can be performed in Python.

Python Program to Count Consecutive Characters Frequency

Count Consecutive Characters using list comprehension + groupby() 

This is one of the shorthand with the help of which this task can be performed. In this, we employ groupby() to group consecutive together to perform frequency calculations.

Python3




from itertools import groupby
 
# initializing string
test_str = "geekksforgggeeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Consecutive characters frequency
res = [len(list(j)) for _, j in groupby(test_str)]
 
# printing result
print("The Consecutive characters frequency : " + str(res))


Output

The original string is : geekksforgggeeks
The Consecutive characters frequency : [1, 2, 2, 1, 1, 1, 1, 3, 2, 1, 1]

Count Consecutive Characters frequency using a loop 

Here, we are using a for loop to iterate through the input string. For each character in the input string, we compare it with the next character in the string using an if statement. If the current character is the same as the next character, we increment the count variable by 1. If the current character is different from the next character, we append the current value of count to the res list and reset the value of count to 1. After iterating through the entire string, we append the final value of the count to the res list. Finally, we print the result using the print statement with a message.

Python3




# initializing string
test_str = "geekksforgggeeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Consecutive characters frequency using loop
res = []
count = 1
for i in range(len(test_str)-1):
    if test_str[i] == test_str[i+1]:
        count += 1
    else:
        res.append(count)
        count = 1
res.append(count)
 
# printing result
print("The Consecutive characters frequency : " + str(res))


Output

The original string is : geekksforgggeeks
The Consecutive characters frequency : [1, 2, 2, 1, 1, 1, 1, 3, 2, 1, 1]

Python Consecutive identical elements using regex 

Another way to solve this problem is using regex. In this, we employ the regex character-finding technique and find the count using len()

Python3




import re
 
# initializing string
test_str = "geekksforgggeeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Consecutive characters frequency Using regex
res = [len(sub.group()) for sub in re.finditer(r'(.)\1*', test_str)]
 
# printing result
print("The Consecutive characters frequency : " + str(res))


Output

The original string is : geekksforgggeeks
The Consecutive characters frequency : [1, 2, 2, 1, 1, 1, 1, 3, 2, 1, 1]

Using itertools.groupby() to Count Consecutive Characters frequency

Import the itertools module. Initialize the input string. Use the itertools.groupby() function to group the consecutive characters in the string. Convert the grouped characters into a list and get the length of the list for each group of consecutive characters. Store the length of each group in a list. Print the list of lengths as the result.

Python3




import itertools
 
# initializing string
test_str = "geekksforgggeeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Consecutive characters frequency Using itertools.groupby()
res = [len(list(group)) for key, group in itertools.groupby(test_str)]
 
# printing result
print("The Consecutive characters frequency : " + str(res))


Output

The original string is : geekksforgggeeks
The Consecutive characters frequency : [1, 2, 2, 1, 1, 1, 1, 3, 2, 1, 1]

Count Consecutive Characters using Counter() function

Import the collections module to use the Counter() function. Initialize an empty list ‘res’ to store the frequency of consecutive characters. Use the Counter() function to count the occurrence of each character in the string. Use a loop to iterate through the string, and check if the current character is equal to the next character. If it is, increment the count of consecutive characters, else append the count to the ‘res’ list, and reset the count to 1. Append the last count to the ‘res’ list. Print the ‘res’ list.

Python3




from collections import Counter
 
test_str = "geekksforgggeeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Consecutive characters frequency using Counter() and loop
res = []
count = 1
 
# using Counter() to count occurrence of each character
c = Counter(test_str)
 
# iterating through the string
for i in range(len(test_str)-1):
    # checking if the current character is equal to the next character
    if test_str[i] == test_str[i+1]:
        count += 1
    else:
        res.append(count)
        count = 1
 
res.append(count)
 
# printing result
print("The Consecutive characters frequency : " + str(res))


Output

The original string is : geekksforgggeeks
The Consecutive characters frequency : [1, 2, 2, 1, 1, 1, 1, 3, 2, 1, 1]



Similar Reads

Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
Given a string S, the task is to find the prefix of string S with the maximum possible length such that frequency of each character in the prefix is at most the number of characters in S with minimum frequency. Examples: Input: S = 'aabcdaab' Output: aabcd Explanation: Frequency of characters in the given string - {a: 4, b: 2, c: 1, d: 1} Minimum f
8 min read
Python - Similar Consecutive elements frequency
Sometimes, while working with Python, we can have a problem in which we have to find the occurrences of elements that are present consecutively. This problem have usage in school programming and data engineering. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This is brute force method by which this problem c
5 min read
Python - Replace identical consecutive elements in list with product of the frequency and Item
Given a list, the task is to write a Python program to replace the grouping of the consecutive elements with a product of the frequency and Item. Input : test_list = [3, 3, 3, 3, 6, 7, 5, 5, 5, 8, 8, 6, 6, 6, 6, 6, 1, 1, 1, 2, 2]Output : [12, 6, 7, 15, 16, 30, 3, 4]Explanation : 3 occurs 4 times in consecution hence, 3*4 = 12, the result. Input : t
6 min read
Python - Odd Frequency Characters
Sometimes, while working with Python strings, we can have a problem in which we need to extract all the string characters which have odd number of occurrences. This problem can have applications in domains such as data domain and day-day programming. Let's discuss certain ways in which this task can be performed. Illustrations: Input : test_str = '
6 min read
Python - Successive Characters Frequency
Sometimes, while working with Python strings, we can have a problem in which we need to find the frequency of next character of a particular word in string. This is quite unique problem and has the potential for application in day-day programming and web development. Let's discuss certain ways in which this task can be performed. Input : test_str =
6 min read
Python - Specific Characters Frequency in String List
Given a String list, extract frequency of specific characters in the whole strings list. Input : test_list = ["geeksforgeeks is best for geeks"], chr_list = ['e', 'b', 'g', 'f'] Output : {'g': 3, 'e': 7, 'b': 1, 'f' : 2} Explanation : Frequency of certain characters extracted. Input : test_list = ["geeksforgeeks"], chr_list = ['e', 'g'] Output : {'
5 min read
Python | Split string in groups of n consecutive characters
Given a string (be it either string of numbers or characters), write a Python program to split the string by every nth character. Examples: Input : str = "Geeksforgeeks", n = 3 Output : ['Gee', 'ksf', 'org', 'eek', 's'] Input : str = "1234567891234567", n = 4 Output : [1234, 5678, 9123, 4567] Method #1: Using list comprehension C/C++ Code # Python
2 min read
Python | Minimum Sum of Consecutive Characters
Sometimes, we might have a problem in which we require to get the minimum sum of 2 numbers from list but with the constraint of having the numbers in successions. This type of problem can occur while competitive programming. Let’s discuss certain ways in which this problem can be solved. Method #1: Using min() + zip() + list comprehension This prob
5 min read
Python | Count K character between consecutive characters
Sometimes, while working with strings, we can have a problem in which we need to check the count of each character between the consecutive character. This type of problem can have application in day-day and web development domain. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop This is brute force way in which
3 min read
Python - Consecutive Repetition of Characters
Sometimes, while working with character lists we can have a problem in which we need to perform consecutive repetition of characters. This can have applications in many domains. Let us discuss certain ways in which this task can be performed. Method #1: Using list comprehension This is one of the way in which this task can be performed. In this, we
5 min read
Practice Tags :
three90RightbarBannerImg