Created
July 17, 2013 20:33
-
-
Save gmvi/6024195 to your computer and use it in GitHub Desktop.
Python function to parse nested parentheses.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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