中缀表达式转换为后缀表达式并求值代码
时间: 2024-04-21 12:20:16 浏览: 100
中缀表达式转换为后缀表达式并求值的代码可以通过使用栈来实现。下面是一个示例的代码:
```python
def infix_to_postfix(expression):
# 定义运算符的优先级
precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
# 初始化一个空栈和一个空列表用于存储后缀表达式
stack = []
postfix = []
for char in expression:
# 如果是操作数,直接添加到后缀表达式列表中
if char.isalnum():
postfix.append(char)
# 如果是左括号,入栈
elif char == '(':
stack.append(char)
# 如果是右括号,将栈中的运算符弹出并添加到后缀表达式列表中,直到遇到左括号
elif char == ')':
while stack and stack[-1] != '(':
postfix.append(stack.pop())
stack.pop() # 弹出左括号
# 如果是运算符,将栈中优先级大于等于当前运算符的运算符弹出并添加到后缀表达式列表中,然后将当前运算符入栈
else:
while stack and stack[-1] != '(' and precedence[char] <= precedence.get(stack[-1], 0):
postfix.append(stack.pop())
stack.append(char)
# 将栈中剩余的运算符弹出并添加到后缀表达式列表中
while stack:
postfix.append(stack.pop())
return ''.join(postfix)
def evaluate_postfix(expression):
stack = []
for char in expression:
if char.isdigit():
stack.append(int(char))
else:
operand2 = stack.pop()
operand1 = stack.pop()
if char == '+':
result = operand1 + operand2
elif char == '-':
result = operand1 - operand2
elif char == '*':
result = operand1 * operand2
elif char == '/':
result = operand1 / operand2
elif char == '^':
result = operand1 ** operand2
stack.append(result)
return stack.pop()
# 测试代码
infix_expression = "3+4*2/(1-5)^2"
postfix_expression = infix_to_postfix(infix_expression)
result = evaluate_postfix(postfix_expression)
print("中缀表达式:", infix_expression)
print("后缀表达式:", postfix_expression)
print("计算结果:", result)
```
阅读全文