python实现直接的中序表达式计算
时间: 2024-05-03 14:17:27 浏览: 22
中序表达式计算需要考虑运算符的优先级和括号的影响,可以通过将中序表达式转换为后序表达式来实现直接计算。
具体实现步骤如下:
1. 定义运算符优先级,例如:{'+' : 1, '-' : 1, '*' : 2, '/' : 2}
2. 定义一个栈,存储运算符和数字
3. 遍历中序表达式,对于每个字符:
- 如果是数字,入栈
- 如果是左括号,入栈
- 如果是右括号,依次出栈直到遇到左括号,将出栈的运算符进行计算,并将计算结果入栈
- 如果是运算符,比较与栈顶运算符优先级,如果优先级较高或相等,将栈顶运算符出栈并计算,直到栈顶运算符优先级较低或栈为空,然后将当前运算符入栈
4. 遍历结束后,如果栈中还有运算符,依次出栈并计算,最终栈中只剩下一个数字,即为表达式的计算结果。
下面是具体实现的代码示例:
```python
def infix_to_postfix(expr):
# 运算符优先级
precedence = {'+' : 1, '-' : 1, '*' : 2, '/' : 2}
# 栈
stack = []
# 后序表达式
postfix = []
# 遍历中序表达式
for c in expr:
if c.isdigit():
# 数字直接加入后序表达式
postfix.append(c)
elif c == '(':
# 左括号入栈
stack.append(c)
elif c == ')':
# 右括号依次出栈直到遇到左括号,将出栈的运算符加入后序表达式
while stack[-1] != '(':
postfix.append(stack.pop())
stack.pop() # 弹出左括号
else:
# 运算符比较与栈顶运算符优先级,如果优先级较高或相等,将栈顶运算符加入后序表达式
while stack and stack[-1] != '(' and precedence[c] <= precedence[stack[-1]]:
postfix.append(stack.pop())
stack.append(c) # 当前运算符入栈
# 将栈中剩余的运算符加入后序表达式
while stack:
postfix.append(stack.pop())
return postfix
def evaluate_postfix(postfix):
# 栈
stack = []
# 遍历后序表达式
for c in postfix:
if c.isdigit():
# 数字直接入栈
stack.append(int(c))
else:
# 运算符弹出栈顶两个数字进行计算,将计算结果入栈
b = stack.pop()
a = stack.pop()
if c == '+':
stack.append(a + b)
elif c == '-':
stack.append(a - b)
elif c == '*':
stack.append(a * b)
elif c == '/':
stack.append(a / b)
return stack.pop()
expr = '2*(3+4)-5'
postfix = infix_to_postfix(expr)
result = evaluate_postfix(postfix)
print(result) # 输出:9
```
以上代码中,先定义了运算符优先级字典 `precedence`,然后定义了两个函数,`infix_to_postfix` 将中序表达式转换为后序表达式,`evaluate_postfix` 对后序表达式进行计算。
最后,对于表达式 `2*(3+4)-5`,先将其转换为后序表达式 `2 3 4 + * 5 -`,然后对后序表达式进行计算得到结果为 `9`。