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

Time:06-03

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?

CodePudding user response:

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

CodePudding user response:

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))

Note that this solution takes a single pass through every character in the string, so it also has optimal complexity!


  • Related