S-exression parsing
Michael Spencer
mahs at telcopartners.com
Fri Mar 11 17:28:55 EST 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 == '(':
stacks.append(stack)
stack = []
elif token == ')':
stacks[-1].append(stack)
stack = stacks.pop()
elif token:
stack.append(token)
return stack[0]
Michael
More information about the Python-list
mailing list