Python operators

Question:

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?

Asked By: Abhi

||

Answers:

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.

Answered By: Greg Hewgill

Just use eval along with string generation:

postfix_expression = "34*34*+"
stack = []
for char in postfix_expression:
    if char in '+-*/':
        expression = '%d%s%d' % (stack.pop(), char, stack.pop())
        stack.append(eval(expression))
    else:
        stack.append(int(char))
print stack.pop()

EDIT: made an even nicer version without the exception handling.

Answered By: DzinX
# This code is untested
from operator import add, sub, mul, div
# read the docs; this is a tiny part of the operator module

despatcher = {
    '+': add,
    '-': sub,
    # etc
    }

opfunc = despatcher[op_char]
operand2 = stack.pop()
stack[-1] = opfunc(stack[-1], operand2)
Answered By: John Machin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.