def solve(polish_notation): polish_notation = polish_notation.split() operands = [] operators = [] operations = { '+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: x / y } last_read = None for element in polish_notation: if element.isdigit(): operands.append(int(element)) while len(operands) > 1 and last_read.isdigit(): second = operands.pop() first = operands.pop() operator = operators.pop() operands.append(operations[operator](first, second)) else: operators.append(element) last_read = element return operands.pop() if __name__ == '__main__': print(solve('* + 3 5 - 7 2')) print(solve('- * / 15 - 7 + 1 1 3 + 2 + 1 1'))