Search code examples
pythonalgorithmarithmetic-expressions

A program to evaluate arithmetic expression


Here's an interesting problem I haven't managed to deal with yet.

Given an arithmetic expression in Reverse Polish Notation, write a program to evaluate it.

The expression is given as a list of numbers and operands. For example [5, 3, '+'] should return 5 + 3 = 8.

For example,

[15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']

should return 5 since it is equivalent to ((15 / (7 - (1 + 1))) * 3) - (2 + (1 + 1)) = 5.


Solution

  • This code would do the job:

    ops = {
        "+": (lambda a, b: a + b),
        "-": (lambda a, b: a - b),
        "*": (lambda a, b: a * b),
        "/": (lambda a, b: a / b)
    }
    
    
    def pol(tokens):
        stack = []
    
        for token in tokens:
            # Check if the current element is an operator
            if token in ops:
                # Take the last two elements from the list
                arg2 = stack.pop()
                arg1 = stack.pop()
                # Execute an operation based on the current operator
                result = ops[token](arg1, arg2)
                # Append the result to the list in order to keep working with it
                stack.append(result)
            else:
                # If it is a number, just append in to the list
                stack.append(int(token))
    
        return stack.pop()
    
    
    print(pol([15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']))