Python bulk method to remove all sequential duplicates

Python Methods and Functions

Examples:

 Input: aaaaabbbbbb Output: ab Input: pythonengineering Output: geksforgeks Input: aabccba Output: abcba 

We have a solution to this problem, please refer to groupby> itertools.groupby () method .

How does itertools.groupby (iterable, key [optional]) work in Python?

Grouping by method takes two inputs: one is iterative (list, tuple, dictionary), and the second — a key function that computes keys for each element present in the iterable. Returns the key and repeatability of the grouped items. If a key function is not specified or is set to None, the key is used by default, and the item is returned unchanged. For example,

numbers = [ 1 , 1 , 1 , 3 , 3 , 2 , 2 , 2 , 1 , 1 ]

import itertools

for (key, group) in itertoo ls.groupby (numbers):

print (key, list (group))

Output:

 (1, [1, 1, 1]) (3, [3, 3] ) (2, [2, 2]) (1, [1, 1]) 

# function to remove all consecutive duplicates
# from string in Python

 

from itertools import groupby

def removeAllConsecutive ( input ):

  

  # group all sequential characters based on their

  # order in the line and we are only interested in

# about the first character each consecutive substring

# on this line, so the key value will work for us

# and we will join these keys without a space

# generate the resulting string

result = []

  for (key, group) in groupby ( input ):

result.append (key)

 

print ('' .join (result))

 
# Driver program

if __ name__ = = "__ main__" :

input = 'aaaaabbbbbb'

removeAllConsecutive ( input )

Links:
https://docs.python.org/3/library/itertools. html

Output:

 ab 




Tutorials