Removing pairs of non-duplicate characters from a str?

Category: python (0 Views)

I'm currently working on the following problem, and have hit a bit of a roadblock:

You will be given three strings, the first string is a sentence known as text that contains at least one occurrence of leftPattern and rightPattern. Left pattern and right pattern are single characters strings that you are attempting to remove from the string. Your goal is to remove only the patterns when left pattern has an equal number of corresponding right patterns. The patterns are removed in pairs only when there is a balanced number of left and right patterns. The patterns may be nested within the text and there is no guarantee that a left pattern will occur before the right pattern.

Example: text = { { Muscat } } { } mecum tollgate } poultry quarrymen pantheon asteria

leftPattern = {

rightPattern = }

return = Muscat mecum tollgate } poultry quarrymen pantheon asteria

This what I have so far:

def nestedRemoval (text:str, leftPattern:str, rightPattern:str) -> str:
lp_count = text.count (leftPattern)
rp_count = text.count (rightPattern)
if lp_count and rp_count:
    for leftPattern in text:
        pair = text.find (rightPattern)

But I'm a bit stumped on where to go from here. Any suggestions? Thanks!

🔴 No definitive solution yet

📌 Solution 1

Use a nesting depth counter to detect when you encounter an extra right pattern.

def nestedRemoval (text:str, leftPattern:str, rightPattern:str) -> str:
    depth = 0
    result = ''
    for char in text:
        if char == leftPattern:
            depth += 1
        elif char == rightPattern and depth > 0:
            depth -= 1
        else:
            result += char
    return result