Skip to content

Instantly share code, notes, and snippets.

@mattdeboard
Created May 13, 2012 14:57
Show Gist options
  • Select an option

  • Save mattdeboard/2688814 to your computer and use it in GitHub Desktop.

Select an option

Save mattdeboard/2688814 to your computer and use it in GitHub Desktop.
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