下面是一个Python后缀表示法解释器,它使用堆栈来计算表达式。是否有可能使此功能更高效、更准确?
#!/usr/bin/env python
import operator
import doctest
class Stack:
"""A stack is a collection, meaning that it is a data structure that
contains multiple elements.
"""
def __init__(self):
"""Initialize a new empty stack."""
self.items = []
def push(self, item):
"""Add a new item to the stack."""
self.items.append(item)
def pop(self):
"""Remove and return an item from the stack. The item
that is returned is always the last one that was added.
"""
return self.items.pop()
def is_empty(self):
"""Check whether the stack is empty."""
return (self.items == [])
# Map supported arithmetic operators to their functions
ARITHMETIC_OPERATORS = {"+":"add", "-":"sub", "*":"mul", "/":"div",
"%":"mod", "**":"pow", "//":"floordiv"}
def postfix(expression, stack=Stack(), operators=ARITHMETIC_OPERATORS):
"""Postfix is a mathematical notation wherein every operator follows all
of its operands. This function accepts a string as a postfix mathematical
notation and evaluates the expressions.
1. Starting at the beginning of the expression, get one term
(operator or operand) at a time.
* If the term is an operand, push it on the stack.
* If the term is an operator, pop two operands off the stack,
perform the operation on them, and push the result back on
the stack.
2. When you get to the end of the expression, there should be exactly
one operand left on the stack. That operand is the result.
See http://en.wikipedia.org/wiki/Reverse_Polish_notation
>>> expression = "1 2 +"
>>> postfix(expression)
3
>>> expression = "5 4 3 + *"
>>> postfix(expression)
35
>>> expression = "3 4 5 * -"
>>> postfix(expression)
-17
>>> expression = "5 1 2 + 4 * + 3 -"
>>> postfix(expression, Stack(), ARITHMETIC_OPERATORS)
14
"""
if not isinstance(expression, str):
return
for val in expression.split(" "):
if operators.has_key(val):
method = getattr(operator, operators.get(val))
# The user has not input sufficient values in the expression
if len(stack.items) < 2:
return
first_out_one = stack.pop()
first_out_two = stack.pop()
operand = method(first_out_two, first_out_one)
stack.push(operand)
else:
# Type check and force int
try:
operand = int(val)
stack.push(operand)
except ValueError:
continue
return stack.pop()
if __name__ == '__main__':
doctest.testmod()
一般建议:
in
运算符:使用它。python -m cProfile -s cumulative foo.py
具体要点:
list
makes a good stack开箱即用。特别是,它允许您使用切片表示法(tutorial)用一个步骤替换pop
/pop
/append
舞蹈。ARITHMETIC_OPERATORS
可以直接引用运算符实现,而无需getattr
间接引用。把这些放在一起:
列表可以直接用作堆栈:
也可以将运算符函数直接放入算术运算符dict:
那么
它们的目的不是让事情变得更有效率(尽管它可能有这种效果),而是让读者更清楚地看到它们。去掉不必要的间接作用和包装。这将有助于减少代码的混淆。它还将在性能上提供(微不足道的)改进,但除非您对其进行度量,否则不要相信这一点。
顺便说一下,使用列表作为堆栈是相当common的惯用Python。
您可以直接映射运算符:
{"+": operator.add, "-": operator.sub, ...}
。这更简单,不需要不必要的getattr
,而且还允许添加额外的函数(不需要破解操作模块)。 您还可以删除一些临时变量,这些临时变量无论如何只能使用一次:另外(性能方面的问题更少,样式方面的问题更多,也是主观的),我完全不会在循环中进行错误处理,而是用
except KeyError
块(未知操作数)、一个except IndexError
块(空堆栈)将其包装在一个try块中。。。但准确吗?它会给出错误的结果吗?
相关问题 更多 >
编程相关推荐