用Python写一串 中缀式完成算术表达式计算,并输出结果。 将算术表达式转换成后缀式,并计算结果。 例:(56-20)/(4+2)转换成:56 20 - 4 2 + / 的代码
时间: 2024-09-25 22:17:46 浏览: 49
算术表达式中缀转后缀并计算结果
在Python中,我们可以使用Shunting Yard算法(也称作中缀转后缀或逆波兰表示法)来实现中缀表达式的计算。这个算法的基本思想是先处理操作数,后处理运算符,将它们按照特定顺序放入栈中。下面是一个简单的实现:
```python
def precedence(op):
# 对于操作符的优先级进行排序
if op == '+' or op == '-':
return 1
elif op == '*' or op == '/':
return 2
else:
return 0
def apply_operator(operators, values):
operator = operators.pop()
right = values.pop()
left = values.pop()
if operator == '+':
values.append(left + right)
elif operator == '-':
values.append(left - right)
elif operator == '*':
values.append(left * right)
elif operator == '/':
values.append(left / right)
def infix_to_postfix(expression):
operators = []
values = []
i = 0
while i < len(expression):
token = expression[i]
if token.isdigit():
values.append(int(token))
elif token in ['+', '-', '*', '/']:
while (operators and precedence(operators[-1]) >= precedence(token)):
apply_operator(operators, values)
operators.append(token)
elif token == '(':
operators.append(token)
elif token == ')':
while operators[-1] != '(':
apply_operator(operators, values)
operators.pop() # remove '('
i += 1
# Apply any remaining operators
while operators:
apply_operator(operators, values)
return values[0]
# 测试例子
expression = "(56-20)/(4+2)"
postfix_expression = infix_to_postfix(expression.split())
result = eval(' '.join(map(str, postfix_expression)))
print(f"原表达式 {expression} 转换成后缀表达式:{postfix_expression}")
print(f"计算结果为:{result}")
阅读全文