- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Python program to count pairs for consecutive elements

Suppose we have a numeric string s contains few digits. The digits may occur multiple times. We have to return some pairs (digit, count) represents which digit has occurred consecutively how many times in s. To solve this problem we can use the groupby() function that comes under itertools library. This will return one iterator object inside that each item will be at first place and another groupby objects at the second place. We have to count number of groupby objects for each pair.

So, if the input is like s = "11522226551", then the output will be [(1, 2), (5, 1), (2, 4), (6, 1), (5, 2), (1, 1)] because at the beginning 1 is present twice, then single 5 then four 2s and so on.

To solve this, we will follow these steps −

- it := call groupby function for s
- ret := a new list
- for each pair (digit, gp) in it, do
- insert (digit and length of the list of gp) into ret

- return ret

## Example

Let us see the following implementation to get better understanding

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))

## Input

"11522226551"

## Output

[(1, 2), (5, 1), (2, 4), (6, 1), (5, 2), (1, 1)]

- Related Questions & Answers
- Program to count index pairs for which array elements are same in Python
- Python – Consecutive identical elements count
- Program to count indices pairs for which elements sum is power of 2 in Python
- Count Pairs of Consecutive Zeros in C++
- Python – Reorder for consecutive elements
- Python program to count Bidirectional Tuple Pairs
- Program to find array by swapping consecutive index pairs in Python
- Python program to count the pairs of reverse strings
- Program to count operations to remove consecutive identical bits in Python
- Program to pack same consecutive elements into sublist in Python
- Program to count nice pairs in an array in Python
- Program to count pairs with XOR in a range in Python
- Count of pairs in an array that have consecutive numbers using JavaScript
- Python Program to Count number of binary strings without consecutive 1’
- Swap Consecutive Even Elements in Python