Remove parentheses around the very first element in the expression tree and in each of its subexpression trees in Python

The goal is to implement a simplification operation: remove parentheses around the very first element in the expression tree and in each of its subexpression trees, where the expression is specified as a line input enclosed in various parentheses. This should work for an arbitrary number of parentheses, for example:

(12) 3 ((45) 6) β†’ 123 (456), remove the parentheses around 12, then about 45

((12) 3) 4 (((5) 67) 8) β†’ 1234 (5678), remove the parentheses around 12, then 123, then 5, then 567. Do not remove the parentheses around 5678, as this is the second element.

How to do it?

EDIT: So far, I have the following:

def simplify(expression):
    """
    call itself recursively until no consecutive parentheses exist
    """
    result = []
    consec_parens = 0
    inside_nested = False
    for char in expression:
        if char == ')' and inside_nested:
            inside_nested = False
            consec_parens = 0
            continue
        if char == '(':
            consec_parens += 1
        else:
            consec_parens = 0
        if consec_parens == 2:
            inside_nested = True
        else:
            result.append(char)
    result = ''.join(result)
    if result == expression:
        return result
    return simplify(result)

, , , (AB) C, AB. ((AB) C) AB, (ABC).

+4
1

( ), , ( . , pushdown automaton ( , ) , :

  • - , . , ) .
  • . , , , . ( .
  • . , , . , , , .

, ( , , ) , . , , β†’ β†’ .

Python:

from enum import Enum

class State(Enum):
    Before = 0
    Inside = 1
    Done   = 2

def simplify(expression):
    levels = [State.Before]
    result = []

    for c in expression:
        if c == '(':
            if levels[-1] == State.Before:
                levels[-1] = State.Inside
            else:
                result.append(c)
            levels.append(State.Before)
        elif c == ')':
            levels.pop()
            if levels[-1] == State.Inside:
                levels[-1] = State.Done
            else:
                result.append(c)
        else:
            if levels[-1] == State.Before:
                levels[-1] = State.Done
            result.append(c)

    return ''.join(result)

, :

>>> simplify('(12)3((45)6)')
'123(456)'
 >>> simplify('((12)3)4(((5)67)8)')
'1234(5678)'
>>> simplify('(AB)C')
'ABC'
>>> simplify('((AB)C)')
'ABC'
0

Source: https://habr.com/ru/post/1658061/


All Articles