python中缀表达式转后缀并解出结果的代码
时间: 2024-11-24 08:40:23 浏览: 10
在Python中,我们可以使用栈数据结构来实现中缀表达式到后缀(逆波兰)表达式的转换,然后使用递归计算求值。以下是一个简单的实现:
```python
def infix_to_postfix(expression):
prec = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} # 运算符优先级
output = [] # 后缀表达式列表
op_stack = [] # 运算符栈
for char in expression:
if char.isdigit():
output.append(char) # 数字直接添加
elif char == '(':
op_stack.append(char)
elif char == ')':
while op_stack and op_stack[-1] != '(':
output.append(op_stack.pop())
op_stack.pop() # 出栈左括号
else: # 遇到运算符
while (op_stack and op_stack[-1]]): # 当前运算符比栈顶小或相等,则先出栈
output.append(op_stack.pop())
op_stack.append(char) # 将当前运算符压入栈
while op_stack: # 右括号已处理完,再将剩余运算符出栈
output.append(op_stack.pop())
return ''.join(output)
def evaluate postfix_expression(postfix_exp):
stack = []
for char in postfix_exp:
if char.isdigit():
stack.append(int(char))
else:
val2 = stack.pop()
val1 = stack.pop()
result = apply_operator(val1, val2, char)
stack.append(result)
return stack[0]
def apply_operator(val1, val2, operator):
if operator == '+':
return val1 + val2
elif operator == '-':
return val1 - val2
elif operator == '*':
return val1 * val2
elif operator == '/':
return val1 / val2
elif operator == '^':
return val1 ** val2
# 示例
expression = "3+5*(2^(4+9))"
postfix = infix_to_postfix(expression)
print(f"Postfix expression: {postfix}")
result = evaluate(postfix)
print(f"Result of the expression: {result}")
阅读全文