Here is a solution that may work for you. I've tried to change your code as little as possible.
Change #1: Rather than check whether symbol
is between 0 and 9, you might simply try to convert symbol
(which starts as a string
) to an int
. If that succeeds, you can treat symbol
as an operand. (This allows your code to handle multi-digit numbers.)
Change #2: Raise an error if a non-number, non-operator occurs in text
. (You don't want anything else to be in there.)
Change #3: Use eval
instead of writing out each of the operators. eval
comes with a lot of safety concerns, but I think here, since we're making sure everything is a number or an operator, we're OK.
Change #4: Push intermediate results into the stack.
Change #5: Return s.pop()
after the list has been exhausted. You might want to add a line that confirms that s
contains just one value at this point.
Caveat: Note that this code assumes that s
will contain two values every time an operator is encountered. You might want to catch the error that would be raised if this were not true with another try
/except
pair of statements.
def evalPostfix(text):
s = Stack()
for symbol in text:
try:
result = int(symbol)
except ValueError:
if symbol not in '+-*/':
raise ValueError('text must contain only numbers and operators')
result = eval('%d %s %d' % (s.pop(), symbol, s.pop()))
s.push(result)
return s.pop()