---------- Forwarded message ---------- From: "Palm Tree" <timeofsa...@gmail.com> Date: 16 Apr 2017 10:07 Subject: Re: [Tutor] bracket issue To: "Peter Otten" <__pete...@web.de> Cc:
Ok thanks for the answers. Perfect. Just to clarify why i wanted recursion was that well coming to compiler theory, i created a python-based language called newB it allows you to define your own keywords but don't abuse like you can configure if to cheese cheese x == 4: coming to recursion well i currently use eval() so everything ok i don't have to worry about brackets but i want to write my own parser. a top down parser for expressions. you can also view the lang here: http://wp.me/p7UB6x-oV thanks for the answers once more On 15 Apr 2017 18:46, "Peter Otten" <__pete...@web.de> wrote: > 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() > > _______________________________________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor