How to recursively remove the first set of parantheses in string of nested parantheses? (in Python)
<p>EDIT: 
Say I have a string of nested parentheses as follows: ((AB)CD(E(FG)HI((J(K))L))) (assume the parantheses are balanced and enclose dproperly
How do i recursively remove the first set of fully ENCLOSED parantheses of every subset of fully enclosed parentheses?</p>

<p>So in this case would be (ABCD(E(FG)HI(JK)). (AB) would become AB because (AB) is the first set of closed parentheses in a set of closed parentheses (from (AB) to K)), E is also the first element of a set of parentheses but since it doesn't have parentheses nothing is changed, and (J) is the first element in the set ((J)K) and therefore the parentheses would be removed.</p>

<p>This is similar to building an expression tree and so far I have parsed it into a nested list and thought I can recursively check if the first element of every nested list isinstance(type(list)) but I don't know how?</p>

<p>The nested list is as follows:</p>

<pre><code>arr = [['A', 'B'], 'C', 'D', ['E', ['F', 'G'], 'H', 'I', [['J'], 'K']]]
</code></pre>

<p>Perhaps convert it into:</p>

<pre><code>arr = [A, B, C, D, [E, [F, G], H, I, [J, K]]
</code></pre>

<p>Is there a better way?</p>

<p>If I understood the question correctly, this ugly function should do the trick:</p>

<pre><code>def rm_parens(s):
    s2 = []
    consec_parens = 0
    inside_nested = False
    for c in s:
        if c == ')' and inside_nested:
            inside_nested = False
            consec_parens = 0
            continue
        if c == '(':
            consec_parens += 1
        else:
            consec_parens = 0
        if consec_parens == 2:
            inside_nested = True
        else:
            s2.append(c)
    s2 = ''.join(s2)
    if s2 == s:
        return s2
    return rm_parens(s2)

s = '((AB)CD(E(FG)HI((J)K))'
s = rm_parens(s)
print(s)
</code></pre>

<p>Note that this function will call itself recursively until no consecutive parentheses exist. However, in your example, ((AB)CD(E(FG)HI((J)K)), a single call is enough to produce (ABCD(E(FG)HI(JK)).</p>

python string algorithm recursion