I am learning Python for the past few days and I have written this piece of code to evaluate a postfix expression.
postfix_expression = "34*34*+"
stack = []
for char in postfix_expression :
try :
char = int(char);
stack.append(char);
except ValueError:
if char == '+' :
stack.append(stack.pop() + stack.pop())
elif char == '-' :
stack.append(stack.pop() - stack.pop())
elif char == '*' :
stack.append(stack.pop() * stack.pop())
elif char == '/' :
stack.append(stack.pop() / stack.pop())
print stack.pop()
Is there a way I can avoid that huge if else block? As in, is there module that takes a mathematical operator in the string form and invokes the corresponding mathematical operator or some python idiom that makes this simple?