Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python operators

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?

like image 745
Abhi Avatar asked Jul 07 '09 07:07

Abhi


People also ask

What are the 7 operators in Python?

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.


1 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.

like image 60
Greg Hewgill Avatar answered Sep 30 '22 05:09

Greg Hewgill