ASm - 2 months ago 16

Python Question

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?

Answer

You have a few problems:

- You are discarding the value after you come across an operator. To fix this you have to push the result of any operator back to the stack and then proceed to the next step.
- You do not skip the rest of the logic when come across a number (it is not going to make your code return a wrong answer, but still is not very smart)
- Your function does not return anything.

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()
```

Source (Stackoverflow)

Comments