Skip to content

Instantly share code, notes, and snippets.

@smitec
Created February 20, 2012 03:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smitec/1867527 to your computer and use it in GitHub Desktop.
Save smitec/1867527 to your computer and use it in GitHub Desktop.
Python boolean statement to RPN
parse("( S < 16 and T = \"P\" ) or ( S > 16 and L = 50 )") => ['S<16', 'T="P"', 'and', 'S>16', 'L=50', 'and', 'or']

Expressions need a space around everything. e.g. "i and ( j or k )" not "i and (j or k)"

def parse(statement):
arg = ""
stack = []
output = [""]
consume = False
ops = ["and", "or"]
for g in statement.split(" "):
slashquote = (len(g) - len(g.replace("\\\"","")))/2
quote = (len(g) - len(g.replace("\"","")))-slashquote
if quote % 2 == 1:
consume = not consume
if not consume:
if g in ops:
while len(stack) > 0 and stack[0] in ops:
output = output + [stack.pop(0)]
output = output + [""]
stack = [g] + stack
elif g == "(":
stack = [g] + stack
elif g == ")":
while stack[0] != "(":
temp = stack.pop(0)
if len(stack) == 0:
print "Error Line", i - 1, "Unmatched parenteses"
return None
output = output + [temp]
stack.pop(0)
else:
#combine everything else into a single token ("i" ">" "16" -> "i>16")
output[-1] = output[-1] + g
else:
output[-1] = output[-1] + " " + g
while len(stack) > 0:
output = output + [stack.pop(0)]
return output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment