Login
Register
Problem list
Online status
58122323朱振洋
:
2023-12-22 08:10:44
def precedence(op): if op == '+' or op == '-': return 1 elif op == '*' or op == '/': return 2 else: return 0 def infix_to_postfix(expression): output = [] stack = [] for char in expression: if char.isalnum(): output.append(char) elif char == '(': stack.append(char) elif char == ')': while stack and stack[-1] != '(': output.append(stack.pop()) stack.pop() else: while stack and precedence(stack[-1]) >= precedence(char): output.append(stack.pop()) stack.append(char) while stack: output.append(stack.pop()) return ''.join(output) def evaluate_postfix(expression): stack = [] for char in expression: if char.isdigit(): stack.append(int(char)) else: num2 = stack.pop() num1 = stack.pop() if char == '+': stack.append(num1 + num2) elif char == '-': stack.append(num1 - num2) elif char == '*': stack.append(num1 * num2) elif char == '/': stack.append(num1 / num2) return stack[0] if __name__ == '__main__': T = int(input()) for _ in range(T): expression = input() postfix_expression = infix_to_postfix(expression) result = evaluate_postfix(postfix_expression) print(result)
Post Your Comment