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?
The value that the operator operates on is called the operand. In Python, there are seven different types of operators: arithmetic operators, assignment operators, comparison operators, logical operators, identity operators, membership operators, and boolean operators.
The operator
module has functions that implement the standard arithmetic operators. With that, you can set up a mapping like:
OperatorFunctions = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.div,
# etc
}
Then your main loop can look something like this:
for char in postfix_expression:
if char in OperatorFunctions:
stack.append(OperatorFunctions[char](stack.pop(), stack.pop()))
else:
stack.append(char)
You will want to take care to ensure that the operands to subtraction and division are popped off the stack in the correct order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With