iotaa
iotaa

Reputation: 23

Recursive/itterative function to return contents within brackets?

Im trying to make a function which looks through multiple parenthesis and returns the contents of each set of parenthesis from inside out. So given the input (9*(2*(6*6))), it would return

(6*6)
(2*(6*6))
(9*(2*(6*6)))

I have this so far but im not sure how to make it work for multiple pairs of brackets. It only return the inner most bracket.

def in_brackets(str) :   
    close_b = 0
    open_b = 0

    if len(str) < 5 : 
        return True

    while str[close_b] != ')':
        close_b += 1
        if str[close_b] == '(':
            open_b = close_b    

    in_b = str[open_b:close_b + 1]

    return(in_b)

Upvotes: 1

Views: 1072

Answers (3)

AChampion
AChampion

Reputation: 30268

A pretty simple recursive function:

def parens(expr):
    if not expr:
        return
    parens(expr[expr.find('(', 1):expr.rfind(')', 0, len(expr)-1)+1])
    print(expr)

>>> parens('(9*(2*(6*6)))')
(6*6)
(2*(6*6))
(9*(2*(6*6)))
>>> parens('((1+2)*(3+4))')
(1+2)*(3+4)
((1+2)*(3+4))

Upvotes: 0

kpie
kpie

Reputation: 11110

This will run in linear time.

class stacked(): # Nodes in the stack
    def __init__(self,obj,next):
        self.obj = obj
        self.next = next
    def getObj(self):
        return(self.obj)
    def getNext(self):
        return(self.next)

class stack(): # The stack itself
    def __init__(self):
        self.top=None
    def push(self,obj):
        self.top = stacked(obj,self.top)
    def pop(self):
        if(self.top == None):
            return(None)
        r = self.top.getObj()
        self.top = self.top.getNext()
        return(r)

def Framed(StringIn,l,r):
    s = stack()
    pairs=[]
    for n,k in enumerate(StringIn):
        if(k==l):
            s.push([n])
        if(k==r):
            q = s.pop()
            q.append(n+1)
            pairs.append(q)
    StringsOut = []
    for k in pairs:
        StringsOut.append(StringIn[k[0]:k[1]])
    return(StringsOut)
s = "((1+2)*(3+4))"
print(Framed(s,"(",")"))

Upvotes: 0

dawg
dawg

Reputation: 104032

You can use pyparsing like so:

>>> from pyparsing import nestedExpr
>>> nestedExpr('(',')').parseString('(9*(2*(6*6)))').asList()
[['9*', ['2*', ['6*6']]]]

Or, great application for a generator:

>>> def pcon(string):
...     stack = []
...     for i, c in enumerate(string):
...         if c == '(':
...             stack.append(i)
...         elif c == ')' and stack:
...             start = stack.pop()
...             yield string[start + 1: i]
... 
>>> for s in pcon('(9*(2*(6*6)))'):
...    print "({})".format(s)
... 
(6*6)
(2*(6*6))
(9*(2*(6*6)))

Upvotes: 1

Related Questions