到目前为止我所拥有的是:
Stack = ArrayStack()
def evaluate(postfix_str, Stack):
for c in postfix_str:
if c not in '+-*/()':
Stack.push(int(c))
else:
c.split(" ")
if c == '+':
sum = Stack.pop() + Stack.pop()
Stack.push(sum)
elif c == '-':
difference = Stack.pop() - Stack.pop()
Stack.push(difference)
elif c == '*':
product = Stack.pop() * Stack.pop()
Stack.push(product)
elif c == '/':
quotient = Stack.pop() / Stack.pop()
Stack.push(quotient)
else:
Stack.push(int(c))
return Stack.pop()
print(evaluate('234*-', Stack)) # 10
这段代码应该找到一个运算符,将其操作数从堆栈中弹出,运行该运算,然后将结果推回到堆栈中。但当我运行代码时,假设我的一个测试用例是('234*-'(,所以我得到的不是-10,而是10。
实际上,10
是正确答案。Stack是一个LIFO(后进先出(结构,在Python实现中,它只是一个继承的list
类,其中push==append
(在末尾添加一个元素(和pop
删除列表的最后一个元素。
Step 1: c=(2) ; Stack = [] ; action = Push(2) ; Stack = [2]
Step 2: c=(3) ; Stack = [2] ; action = Push(3) ; Stack = [2, 3]
Step 3: c=(4) ; Stack = [2, 3] ; action = Push(4) ; Stack = [2, 3, 4]
Step 4: c=(*) ; Stack = [2, 3, 4] ; action = Push(Pop(4) * Pop(3)) ; Stack = [2, 12]
Step 5: c=(-) ; Stack = [2, 12] ; action = Push(Pop(12) - Pop(2)) ; Stack = [10]