中缀表达式求值python
时间: 2023-11-02 12:01:54 浏览: 62
中缀表达式求值是指将表达式中的运算符按照一定的优先级进行计算,得出最终的结果。下面是一个简单的中缀表达式求值的Python代码示例:
```python
def infix_eval(expression):
# 创建一个空栈
stack = []
# 定义运算符的优先级
priority = {"+": 1, "-": 1, "*": 2, "/": 2}
# 遍历表达式中的每个字符
for char in expression:
if char.isdigit():
# 如果字符是数字,直接将其加入栈中
stack.append(int(char))
else:
# 如果字符是运算符,弹出栈顶的两个数字进行运算
right = stack.pop()
left = stack.pop()
# 根据运算符的优先级进行相应的运算
if char == "+":
result = left + right
elif char == "-":
result = left - right
elif char == "*":
result = left * right
elif char == "/":
result = left / right
# 将运算结果压入栈中
stack.append(result)
# 最终栈中的唯一元素即为最终的计算结果
return stack[0]
```