Last active
November 26, 2015 08:28
-
-
Save GaryLee/fdb77a848bd4cf78efa7 to your computer and use it in GitHub Desktop.
solution for http://www.spoj.com/problems/ONP/
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
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