1. elbaschid
  2. codeeval_challenges

Source

codeeval_challenges / 007_PrefixExpressions / prefix_expressions.py

# On CodeEval, test cases are read in from a file which is the first argument to your program
# Open the file and read in line by line. Each line represents a different test case
# (unless given different instructions in the challenge description)

import sys

OPERATORS = {
    '*': lambda x, y: x*y, 
    '/': lambda x, y: x/y, 
    '+': lambda x, y: x+y,
}

def evaluate_expression(expression):
    """ Evaluates a prefix expression provided as a list. Valid operators
        are '/', '*', '+' (divide, multiply, add). Operands have to be 
        integer values. An exception is raised when invalid operator/operand
        are found in expression.

        Returns the result of the prefix expression as integer value. 
    """

    expression = expression.split()

    stack = []
    for value in reversed(expression):

        if value in OPERATORS.keys():
            ## call lambda for corresponding operator
            result = OPERATORS[value](
                stack.pop(),
                stack.pop(),
            )
            stack.append(result)

        else:
            try:
                stack.append(int(value))
            except:
                raise Exception("Invalid operand/operator found: '%s'" % value)

    assert(len(stack) == 1)

    return stack.pop()

def main():
    test_cases = open(sys.argv[1], 'r')

    for test in test_cases:
        test = test.strip()

        if test != '':
            print evaluate_expression(test)

    test_cases.close()

if __name__ == "__main__":
    main()