我正在阅读 An Introduction to Data Structures and Algorithms - Jean-Paul Tremblay,我为该书中描述的 RPN 中缀程序编写了一个 python 实现。
SYMBOL = ['+', '-', '*', '/', '^', 'VAR', '(', ')']
INPUT_PRECEDENCE = [1, 1, 3, 3, 6, 7, 9, 0]
STACK_PRECEDENCE = [2, 2, 4, 4, 5, 8, 0, None]
RANK = [-1, -1, -1, -1, -1, 1, None, None]
INFIX = '(a+b^c^d)*(e+f/d)'
POLISH_TEST = 'abcd^^+efd/+*'
def getIndex (symbol):
if (symbol.isalpha()):
index = 5
else:
index = SYMBOL.index (symbol)
return index
def InfixToReversePolish (INFIX):
#initialize
POLISH = []
STACK = []
#append ')' to infix
INFIX = INFIX + ')'
#push '(' on to the stack
STACK.append (SYMBOL[6])
for i in range(0, len(INFIX)):
#read the next char in the infix
NEXT = INFIX[i]
#what is the index of next in the precedence and rank tables?
index = getIndex (NEXT)
if (len (STACK) == 0):
print ('Invalid input string')
return
#if we encounter ')', we pop the stack till we find '('. we discard both '(' and ')'
if index == 7:
ch = STACK.pop()
while getIndex (ch) != 6:
POLISH.append (ch)
ch = STACK.pop()
continue
#while next input precedence is less than or equal to the top stack precedence
while (INPUT_PRECEDENCE[index] <= STACK_PRECEDENCE[getIndex(STACK[len(STACK) - 1])]):
POLISH.append (STACK.pop())
#push next on to the stack
STACK.append (NEXT)
return POLISH
ex = ''.join (InfixToReversePolish (INFIX))
print ('Reverse Polish Expression is', ex)
Reverse Polish Expression is abcd^^+efd/+*