import math def split_exp(expression): # 将表达式拆分为数字、运算符和三角函数 stack = [] current_item = '' for char in expression: if char.isdigit() or char == '.': current_item += char elif char.isalpha(): # 识别字母表示的函数名 current_item += char elif char == '(': if current_item: stack.append(current_item) current_item = '' stack.append(char) elif char == ')' and current_item: stack.append(current_item) stack.append(char) current_item = '' elif char in OPS: if current_item: stack.append(current_item) current_item = '' stack.append(char) if current_item: stack.append(current_item) return stack def get_postfix_expression(expression): # 多位数拆分 expression = split_exp(expression) precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3,"sin":4,"cos":4,"tan":4} postfix = [] stack = [] def is_number(char): try: float(char) return True except ValueError: return False for char in expression: if is_number(char): postfix.append(char) elif char == '(': stack.append(char) elif char == ')': while stack and stack[-1] != '(': postfix.append(stack.pop()) stack.pop() # 弹出 '(' elif char in precedence: while stack and stack[-1] != '(' and precedence.get(stack[-1], 0) >= precedence.get(char, 0): postfix.append(stack.pop()) stack.append(char) # elif char in ('sin', 'cos', 'tan'): # 处理三角函数 # stack.append(char) while stack: postfix.append(stack.pop()) return postfix exp = 'sin(3.3)^2+cos(3.3)^2' OPS = ['+', '-', '*', '/', '^'] exp_ls = split_exp(exp) print(exp_ls) print(get_postfix_expression(exp)) # ['3.3', 'sin', '2', '^', '3.3', 'cos', '2', '^', '+']