Lists can be used directly as stacks:
>>> stack = [] >>> stack.append(3) # push >>> stack.append(2) >>> stack [3, 2] >>> stack.pop() # pop 2 >>> stack [3]
You can also put operational functions directly in your ARITHMETIC_OPERATORS dict:
ARITHMETIC_OPERATORS = {"+":operator.add, "-":operator.sub, "*":operator.mul, "/":operator.div, "%":operator.mod, "**":operator.pow, "//":operator.floordiv}
then
if operators.has_key(val): method = operators[val]
The goal is not to make things more effective (although this may have such an effect), but to make them more obvious to the reader. Get rid of unnecessary levels of indirection and wrappers. This will make your code less confusing. It will also provide a (trivial) performance improvement, but don't believe that if you don't measure it.
By the way, using lists as stacks is pretty common idiomatic Python.
nmichaels
source share