[Tutor] bracket issue

Peter Otten __peter__ at web.de
Sat Apr 15 10:45:53 EDT 2017


Palm Tree wrote:

> hi all. i'm trying to write a simple program. i'm using python 3.4
> 
> let us say i have
> 
> s="2*3+3(8-4(5+6+9))+2+3+3(4/4)"
> 
> i want to find expression enclosed in brackets.
> 
> i want outputs to be like:
> (8-4(5+6+9))
> (5+6+9)
> (4/4)
> note : i'd like an answer involving recursion if possible

No recursion, but a stack managed manually:

>>> s = "2*3+3(8-4(5+6+9))+2+3+3(4/4)"
>>> stack = []
>>> for i, c in enumerate(s):
...     if c == "(":
...         stack.append(i)
...     elif c == ")":
...         print(s[stack.pop():i+1])
... 
(5+6+9)
(8-4(5+6+9))
(4/4)

The order is determined by the closing parenthesis, you could sort if you 
don't want that.

I did not find a convincing translation using recursion, but I'll give one 
anyway:

def find_closing(s):
    i = c = None
    pairs = enumerate(s)
    def step(start=None):
        nonlocal i, c
        for i, c in pairs:
            if c == "(":
                step(i)
            elif c == ")":
                if start is not None:
                    print(s[start:i+1])
                return
    step()



More information about the Tutor mailing list