Can this Python postfix notation (reverse polish notation) interpreter be made more efficient and accurate?

后端 未结 3 1050
迷失自我
迷失自我 2020-12-15 01:20

Here is a Python postfix notation interpreter which utilizes a stack to evaluate the expressions. Is it possible to make this function more efficient and accurate?

3条回答
  •  轮回少年
    2020-12-15 01:58

    You can directly map the operators: {"+": operator.add, "-": operator.sub, ...}. This is simpler, doesn't need the unnecessary getattr and also allows adding additional functions (without hacking the operator module). You could also drop a few temporary variables that are only used once anyway:

    rhs, lhs = stack.pop(), stack.pop()
    stack.push(operators[val](lhs, rhs)).    
    

    Also (less of a performance and more of a style issue, also subjective), I would propably don't do error handling at all in the loop and wrap it in one try block with an except KeyError block ("Unknown operand"), an except IndexError block (empty stack), ...

    But accurate? Does it give wrong results?

提交回复
热议问题