Function to remove more than 2 consecutive repetitions of a string not working

Viewed 76

Here's my function:

def remove_more_than_two_reps(text):
    result = list(text)
    for idx,char in enumerate(text):       
        if(result[:idx].count(char) > 2):
            result.remove(char) 
    return ''.join(result) 

expected result:

text = 'teeeexxxxt'
result = remove_more_than_two_reps(text)
>'teexxt'

My function just returns the original string, what is the problem?

3 Answers

Try using append which is O(1) instead of remove which is O(n):

def remove_more_than_two_reps(text: str) -> str:
    result = []
    for ch in text:
        if len(result) < 2 or result[-1] != ch or result[-2] != ch:
            result.append(ch)
    return ''.join(result)

text = 'teeeexxxxt'
result = remove_more_than_two_reps(text)
print(result)

Output:

teexxt

Wanted to share an itertools solution, useful when you have particularly big strings (since it avoids allocating an enormous list):

import itertools as it

def remove_more_than_two_reps(text: str) -> str:
    reps_of_at_most_two = (it.islice(reps, 2) for _, reps in it.groupby(text))
    return ''.join(it.chain.from_iterable(reps_of_at_most_two))

Another option could be using a pattern, matching 3 or more times the same character (.)\1{2,} and in the replacement use 2 times the captured group value:

import re

def remove_more_than_two_reps(text):
    return re.sub(r'(.)\1{2,}', r'\1\1', text)

text = 'teeeexxxxt'

print(remove_more_than_two_reps(text))

Output

teexxt

See a regex demo and a Python demo.

Related