Skip to main content
 首页 » 编程设计

python之在 python 中评估后缀

2025年05月04日15mq0036

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

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() 

但我认为我的做法是错误的。帮忙?

请您参考如下方法:

你有几个问题:

  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()