Related Articles

# Python Program to get number of consecutive repeated substring

• Last Updated : 06 Jun, 2021

Given a substring K, the task is to write a Python Program to find the repetition of K string in each consecutive occurrence of K.

Example

Input : test_str = ‘geeksgeeks are geeksgeeksgeeks for all geeks’, K = “geeks”

Output : [2, 3, 1]

Explanation : First consecution of ‘geeks’ is 2.

Input : test_str = ‘geeksgeeks are geeksgeeksgeeksgeeks for all geeks’, K = “geeks”

Output : [2, 4, 1]

Explanation : First consecution of ‘geeks’ is 2, next comes with 4 consecution of geeks.

Method 1: Using split() + count() + list comprehension

Works only for specific cases in which consecution is separated by spaces. In this, each word is splitted using split(), and each segment is evaluated for repetition count using count().

## Python3

 `# Python3 code to demonstrate working of``# Number of repeated substrings in consecution``# Using split() + count() + list comprehension`` ` `# initializing string``test_str ``=` `'geeksgeeks are geeksgeeksgeeks for all geeks'`` ` `# printing original string``print``(``"The original string is : "` `+` `str``(test_str))`` ` `# initializing K ``K ``=` `"geeks"`` ` `# count() counts repetition``res ``=` `[sub.count(K) ``for` `sub ``in` `test_str.split(``' '``) ``if` `sub.count(K) !``=` `0``]`` ` `# printing result``print``(``"String repetitions : "` `+` `str``(res))`

Output:

The original string is : geeksgeeks are geeksgeeksgeeks for all geeks

String repetitions : [2, 3, 1]

Method 2: Using findall() + regex + len()

In this, all the runs are computed for repetition of substring, and then division of length by substring length gives the measure of repetition number.

## Python3

 `# Python3 code to demonstrate working of``# Number of repeated substrings in consecution``# Using findall() + regex + len()``import` `re`` ` `# initializing string``test_str ``=` `'geeksgeeksaregeeksgeeksgeeksforallgeeks'`` ` `# printing original string``print``(``"The original string is : "` `+` `str``(test_str))`` ` `# initializing K ``K ``=` `'geeks'``n ``=` `len``(K)`` ` `# getting regex``regx ``=` `re.``compile``(f``'((?:{K})+)'``)`` ` `# getting repeats counts``# findall finding all substring joined repetitions``res ``=` `[``len``(occ) ``/``/` `n ``for` `occ ``in` `regx.findall(test_str)]`` ` `# printing result``print``(``"String repetitions : "` `+` `str``(res))`

Output:

The original string is : geeksgeeks are geeksgeeksgeeks for all geeks

String repetitions : [2, 3, 1]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up