Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to count pairs for consecutive elements
When working with numeric strings, you often need to count how many times each digit appears consecutively. Python's itertools.groupby() function is perfect for this task as it groups consecutive identical elements together.
For example, if the input is s = "11522226551", the output should be [(1, 2), (5, 1), (2, 4), (6, 1), (5, 2), (1, 1)] because digit 1 appears twice consecutively at the beginning, then single 5, then four 2s, and so on.
Algorithm
To solve this problem, we will follow these steps ?
- Use
groupby()function to group consecutive identical digits - Create an empty list to store results
- For each group, append a tuple containing the digit and its count
- Return the result list
Example
Here's the complete implementation ?
from itertools import groupby
def solve(s):
it = groupby(s)
ret = []
for digit, gp in it:
ret.append((int(digit), len(list(gp))))
return ret
s = "11522226551"
print(solve(s))
The output of the above code is ?
[(1, 2), (5, 1), (2, 4), (6, 1), (5, 2), (1, 1)]
How It Works
The groupby() function returns an iterator where each item contains the key (digit) and a group object containing all consecutive occurrences. We convert the group to a list and count its length to get the consecutive count for each digit.
Alternative Approach Using Manual Iteration
You can also solve this without groupby() using a simple loop ?
def solve_manual(s):
if not s:
return []
result = []
current_digit = s[0]
count = 1
for i in range(1, len(s)):
if s[i] == current_digit:
count += 1
else:
result.append((int(current_digit), count))
current_digit = s[i]
count = 1
# Add the last group
result.append((int(current_digit), count))
return result
s = "11522226551"
print(solve_manual(s))
[(1, 2), (5, 1), (2, 4), (6, 1), (5, 2), (1, 1)]
Conclusion
Use itertools.groupby() for a concise solution when counting consecutive elements. The manual approach offers more control but requires handling edge cases like empty strings.
