def evaluate_postfix(expression): stack = [] operators = "+-*/" # Supported operators def perform_operation(operator, operand1, operand2): if operator == "+": return operand1 + operand2 elif operator == "-": return operand1 - operand2 elif operator == "*": return operand1 * operand2 elif operator == "/": if operand2 == 0: raise ValueError("Division by zero") return operand1 / operand2 for token in expression.split(): if token not in operators: # If the token is an operand, push it onto the stack stack.append(float(token)) else: # If the token is an operator, pop two operands from the stack and perform the operation if len(stack) < 2: raise ValueError("Not enough operands for operator") operand2 = stack.pop() operand1 = stack.pop() result = perform_operation(token, operand1, operand2) # Push the result back onto the stack stack.append(result) # The final result should be the only item left on the stack