Skip to content

Instantly share code, notes, and snippets.

@gmvi
Created July 17, 2013 20:33
Show Gist options
  • Save gmvi/6024195 to your computer and use it in GitHub Desktop.
Save gmvi/6024195 to your computer and use it in GitHub Desktop.
Python function to parse nested parentheses.
def parse(string):
if not string: return
if string[0] != "(": raise ValueError("malformed string")
parsed = ()
last = 0
count = 0
for i in range(len(string)):
if string[i] == "(": count += 1
if string[i] == ")": count -= 1
if count == 0:
inner = parse(string[last+1:i])
last = i+1
if inner:
parsed += (list(inner),)
else:
parsed += ([],)
if last != len(string): raise ValueError("malformed string")
return parsed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment