Created
May 13, 2012 14:57
-
-
Save mattdeboard/2688814 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 querytree(s): | |
| """ | |
| Build a list of nodes to describe the nested structure of a querystring. | |
| """ | |
| Node = namedtuple("Node", "level value") | |
| stack = [] | |
| # A node has children if there is a left paren before a right paren, | |
| # starting from hte index position where the node begins. | |
| for idx, char in enumerate(s): | |
| if char == "(": | |
| stack.append(idx) | |
| if len(stack) > 1: | |
| start = stack[-2] | |
| substr = s[start+1:idx] | |
| yield Node(len(stack)-1, substr) | |
| elif char == ")": | |
| start = stack.pop() | |
| substr = s[start+1:idx] | |
| yield Node(len(stack), substr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment