I found a small bug in my script, "8 4 /" calculated 4/8 instead of 8/4, so here's the updated version:
def ReversePolish(line):
stack = []
tokens = line.split(" ")
for token in tokens:
try:
#maybe the token is a number, try to convert it from string to number
a = float(token)
stack.append(a)
except ValueError:
#looks like it's not a number, maybe it's an operator
if token in "+-*/":
#check if stack is big enough, 2 elements required!
if len(stack) < 2:
raise SyntaxError
#stack is [blah, blah, blah, a, b], so b has to be popped first
b = stack.pop()
a = stack.pop()
if token == "+":
stack.append(a + b)
elif token == "-":
stack.append(a - b)
elif token == "*":
stack.append(a * b)
elif token == "/":
stack.append(a / b)
else:
raise SyntaxError
#all tokens have been parsed, check stack size and return the result
if len(stack) == 1:
return stack.pop()
else:
raise SyntaxError
if __name__ == "__main__":
line = input("Enter reverse polish: ")
try:
print(ReversePolish(line))
except SyntaxError:
print("Syntax Error!")