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


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"




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

Updated on: 12-Oct-2021


Kickstart Your Career

Get certified by completing the course

Get Started