【发布时间】:2011-10-23 18:14:01
【问题描述】:
我正在用 Python 编写一个计算器(作为练习),有一点我想知道。
程序将输入拆分为数字和运算符列表。然后这样计算结果:
import operator
ops = {'+' : operator.add, # operators and corresponding functions
'-' : operator.sub,
'*' : operator.mul,
'/' : operator.truediv,
'%' : operator.mod}
precedence = [['*', '/', '%'], ['+', '-']] # order of precedence for operators
def evaluate(exp):
for oplist in precedence: # search for operators first in order of precedence
for op in exp: # then from left to right
if op in oplist:
index = exp.index(op)
result = ops[op](exp[index - 1], exp[index + 1])
# compute the result of the operation
exp[index - 1:index + 2] = [result]
# replace operation and operands with result
return exp[0]
# for example,
evaluate([2, '+', 3, '+', 4, '+', 5])
# should return 14
此函数按优先级递减顺序然后从左到右查找算术运算符列表,当它找到这样的运算符时,它会调用相邻列表元素(操作数)上的相应函数并替换运算符和列表中的操作数与操作的结果。执行完所有操作后,列表将包含一个元素 - 计算结果。
但是,此函数的行为与预期不同。问题(我认为)是这个函数在迭代列表时修改了列表(通过分配给切片)。我已经找到了解决这个问题here 的方法(通过在每次修改列表时重新启动内部for 循环),但是给出解决方案的人似乎认为通常应该有更好的方法来完成任何事情这是需要的。
我想知道是否有更好的方法来实现这个算法,以避免奇怪的“重启循环”。
感谢您的任何想法!
【问题讨论】:
-
这确实更适合codereview.stackexchange.com,你想把它迁移到那里吗?
-
啊,我没有考虑过。当然,谢谢。
标签: python implementation calculator