0 votes
1 view
in Python by (19.9k points)

How to split a string in the following way:

a = "111554222117"

My goal is to split string into several pieces, where the continuous repeated will grouped together. The output will be a list

b = ['111','55','4','222','11','7']

PS: not tool can be used like itertools since this is an interview question.

My attempt is to use at least two for loop, but it is not effective. how to use only one loop.


1 Answer

0 votes
by (25.1k points)
edited by

You can just use itertools and list comprehensions for this.

import itertools

[''.join(data) for _, data in itertools.groupby("111554222117")]

To know more about this you can have a look at the following video:-

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !