Algorithm (pseudo code)
based on
Algorithm to convert infix to postfix expression
Also see
Infix and postfix expressions
(pdf)
This code does not detect some syntax errors.
# ==============================================================
# convert numeric infix expression to a
# Reverse Polish Expression (RPN)
#
# Note: TOS is top of stack
# ==============================================================
start-sub is a '(' character
end-sub is a ')' character
# --------------------------------------------------------------
function process_sub_end (stack,rpn_tokens):
while the stack is not empty:
if TOS is start-sub: return True
append token to rpn_tokens
# ---- did not find start-sub
return False
# --------------------------------------------------------------
stack = empty stack
rpn_tokens = empty list
for each token in tokens:
# ---- token is a number
If the token is a number:
append the token to the RPN token list
continue
# --- token is a start-sub
If the token is a start-sub:
push the token onto the stack
continue
# --- token is an end-sub
If the token is an end-sub:
tf = process_sub_end(stack,rpn_tokens)
if tf is False:
return syntax error / exit program
continue
# ---- if the stack is empty
if the stack is empty:
push the token onto stack
continue
# ---- if token is a math operator and
# ---- the token precedence is greater than TOS
if the token is in [**,//,*,/,+,-,%] and
the token as a higher precedence than TOS:
push the token onto the stack
continue
# ---- if the token precedence is less than or equal to TOS
loop:
if the stack is empty: break
if the TOS is sub-start or end-sub: break
if the token precedence is less that or equal to TOS:
pop TOS from the stack
append the token to the RPN token list
else:
break
push the token onto the stack
continue
# ---- move remaining stack tokens to the RPN token list
while the stack is not empty:
if TOS is sub-start: return False
if TOS is sub-start: return False
pop the TOS from the stack
append the TOS to the end of the RPN token list
continue
results = pop the TOS from the stack
If the stack is not empty
there is a syntax error
else
display the results