在python中评估后缀?

ASm*_*ASm 3 python postfix-notation

我想编写一个函数来评估作为列表传递的后缀表达式。到目前为止,我有:

def evalPostfix(text):
    s = Stack()
    for symbol in text:
        if symbol in "0123456789":
            s.push(int(symbol))
        if not s.is_empty():
            if symbol == "+":
                plus = s.pop() + s.pop()
            if symbol == "-":
                plus = s.pop() - s.pop()
            if symbol == "*":
                plus = s.pop() * s.pop()
            if symbol == "/":
                plus = s.pop() / s.pop()
Run Code Online (Sandbox Code Playgroud)

但我认为我有错误的方法。帮助?

Hos*_*ane 5

你有几个问题:

  1. 遇到运算符后,您将丢弃该值。要解决此问题,您必须将任何运算符的结果推回堆栈,然后继续下一步。
  2. 遇到数字时,您不会跳过其余的逻辑(它不会使您的代码返回错误答案,但仍然不是很聪明)
  3. 您的函数不返回任何内容。

这样的事情应该工作:

def eval_postfix(text):
    s = list()
    for symbol in text:
        if symbol in "0123456789":
            s.append(int(symbol))

        plus = None
        elif not s.is_empty():
            if symbol == "+":
                plus = s.pop() + s.pop()
            elif symbol == "-":
                plus = s.pop() - s.pop()
            elif symbol == "*":
                plus = s.pop() * s.pop()
            elif symbol == "/":
                plus = s.pop() / s.pop()
        if plus is not None:
            s.append(plus)
        else:
             raise Exception("unknown value %s"%symbol)
    return s.pop()
Run Code Online (Sandbox Code Playgroud)