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?
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?