Skip to content

Instantly share code, notes, and snippets.

@GaryLee
Last active November 26, 2015 08:28
Show Gist options
  • Save GaryLee/fdb77a848bd4cf78efa7 to your computer and use it in GitHub Desktop.
Save GaryLee/fdb77a848bd4cf78efa7 to your computer and use it in GitHub Desktop.
STATE_OPEREND = 0
STATE_OPERATOR = 1
def to_rpn(expr):
rpn = ['', '', '']
state = STATE_OPEREND
operend_i = 0
while len(expr) > 0:
ch = expr[0]
if state == STATE_OPEREND:
rpn[operend_i], expr = to_rpn(expr[1:]) if ch == '(' else (ch, expr[1:])
if operend_i == 0:
state = STATE_OPERATOR
operend_i = 1
else:
expr = expr[1:] # for ')'
break
elif state == STATE_OPERATOR:
rpn[2], expr = ch, expr[1:]
state = STATE_OPEREND
return ''.join(rpn), expr
inputs = ['(a+(b*c))',
'((a+b)*(z+x))',
'((a+t)*((b+(a+c))^(c+d)))']
for expr in inputs:
print to_rpn(expr)[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment