我想编写一个函数来计算作为列表传递的后缀表达式。到目前为止我已经得到:
def evalPostfix(text):
s = Stack()
for symbol in text:
if symbol in "0123456789":
s.push(int(symbol))
if not s.is_empty():
if symbol == "+":
plus = s.pop() + s.pop()
if symbol == "-":
plus = s.pop() - s.pop()
if symbol == "*":
plus = s.pop() * s.pop()
if symbol == "/":
plus = s.pop() / s.pop()
但我认为我的方法是错误的。帮助?
你有几个问题:
- 在遇到运算符后,您将丢弃该值。要解决此问题,您必须将任何运算符的结果推回堆栈,然后继续下一步。
- 当遇到数字时,您不会跳过其余的逻辑(它不会使您的代码返回错误的答案,但仍然不是很聪明)
- 您的函数不返回任何内容。
像这样的东西应该有效:
def eval_postfix(text):
s = list()
for symbol in text:
if symbol in "0123456789":
s.append(int(symbol))
plus = None
elif not s.is_empty():
if symbol == "+":
plus = s.pop() + s.pop()
elif symbol == "-":
plus = s.pop() - s.pop()
elif symbol == "*":
plus = s.pop() * s.pop()
elif symbol == "/":
plus = s.pop() / s.pop()
if plus is not None:
s.append(plus)
else:
raise Exception("unknown value %s"%symbol)
return s.pop()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)