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

后端 未结 3 1068
迷失自我
迷失自我 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 02:03

    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 the operator functions directly into 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 of these is not to make things more efficient (though it may have that effect) but to make them more obvious to the reader. Get rid of unnecessary levels of indirection and wrappers. That will tend to make your code less obfuscated. It will also provide (trivial) improvements in performance, but don't believe that unless you measure it.

    Incidentally, using lists as stacks is fairly common idiomatic Python.

提交回复
热议问题