- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# 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 Articles
- 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
- Python program to count Bidirectional Tuple Pairs
- Python – Reorder for consecutive elements
- Count Pairs of Consecutive Zeros in C++
- 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 count nice pairs in an array in Python
- Program to pack same consecutive elements into sublist in Python
- Python Program to Count number of binary strings without consecutive 1’
- Python Program to Alternate list elements as key-value pairs
- Program to count pairs with XOR in a range in Python
- Javascript Program to Count pairs with given sum