S-exression parsing

Michael Spencer mahs at telcopartners.com
Fri Mar 11 23:28:55 CET 2005

George Sakkis wrote:
> The S-expression parser below works, but I wonder if it can be simplified; it's not as short and
> straightforward as I would expect given the simplicity of S-expressions. Can you see a simpler
> non-recursive solution ?

How about this (minus your error checking)?

def parseS(expression):
     stack = []
     stacks = []
     for token in re.split(r'([()])|\s+', expression):
         print stack
         if token == '(':
             stack = []
         elif token == ')':
             stack = stacks.pop()
         elif token:
     return stack[0]


More information about the Python-list mailing list