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