I want to write a fucnction to evaluate a postfix expression passed as a list. So far I have got:
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()
But I think I have the wrong approach. Help?
You have a few problems:
Something like this should work:
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()