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

后端 未结 3 1057
迷失自我
迷失自我 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:19

    General suggestions:

    • Avoid unnecessary type checks, and rely on default exception behavior.
    • has_key() has long been deprecated in favor of the in operator: use that instead.
    • Profile your program, before attempting any performance optimization. For a zero-effort profiling run of any given code, just run: python -m cProfile -s cumulative foo.py

    Specific points:

    • list makes a good stack out of the box. In particular, it allows you to use slice notation (tutorial) to replace the pop/pop/append dance with a single step.
    • ARITHMETIC_OPERATORS can refer to operator implementations directly, without the getattr indirection.

    Putting all this together:

    ARITHMETIC_OPERATORS = {
        '+':  operator.add, '-':  operator.sub,
        '*':  operator.mul, '/':  operator.div, '%':  operator.mod,
        '**': operator.pow, '//': operator.floordiv,
    }
    
    def postfix(expression, operators=ARITHMETIC_OPERATORS):
        stack = []
        for val in expression.split():
            if val in operators:
                f = operators[val]
                stack[-2:] = [f(*stack[-2:])]
            else:
                stack.append(int(val))
        return stack.pop()
    

提交回复
热议问题