python3 program to evaluate a prefix expression return true if the given char c is an operand e g it is a number isoperand1 true isoperand false evaluate a given expression in prefix notation asserts that the given expression is valid evaluate 9 2 6 21 evaluate 10 2 4 1 4 0 iterate over the string in reverse order push operand to stack pop values from stack can calculate the result push the result onto the stack again driver code return true if the given char c is an operand e g it is a number is_operand 1 true is_operand false evaluate a given expression in prefix notation asserts that the given expression is valid evaluate 9 2 6 21 evaluate 10 2 4 1 4 0 iterate over the string in reverse order push operand to stack pop values from stack can calculate the result push the result onto the stack again driver code
calc = {
    "+": lambda x, y: x + y,
    "-": lambda x, y: x - y,
    "*": lambda x, y: x * y,
    "/": lambda x, y: x / y,
}


def is_operand(c):
    
    return c.isdigit()


def evaluate(expression):
    
    stack = []

    
    for c in expression.split()[::-1]:
        
        if is_operand(c):
            stack.append(int(c))

        else:
            
            
            o1 = stack.pop()
            o2 = stack.pop()
            stack.append(calc[c](o1, o2))

    return stack.pop()



if __name__ == "__main__":
    test_expression = "+ 9 * 2 6"
    print(evaluate(test_expression))

    test_expression = "/ * 10 2 + 4 1 "
    print(evaluate(test_expression))