实现中缀表达式转后缀表达式,并计算最后结果
时间: 2023-12-18 09:40:38 浏览: 94
好的,我可以为您编写一个函数,实现中缀表达式转后缀表达式,并计算最后的结果。以下是一个示例代码:
```python
def infix_to_postfix(expression):
# 定义运算符的优先级
precedence = {'+': 1, '-': 1, '*': 2, '/': 2}
postfix = [] # 存储后缀表达式
stack = [] # 运算符栈
for char in expression:
if char.isdigit():
postfix.append(char)
elif char in '+-*/':
while stack and stack[-1] != '(' and precedence[char] <= precedence.get(stack[-1], 0):
postfix.append(stack.pop())
stack.append(char)
elif char == '(':
stack.append(char)
elif char == ')':
while stack and stack[-1] != '(':
postfix.append(stack.pop())
stack.pop() # 弹出左括号
while stack:
postfix.append(stack.pop())
return postfix
def evaluate_postfix(postfix):
stack = []
for char in postfix:
if char.isdigit():
stack.append(int(char))
elif char in '+-*/':
num2 = stack.pop()
num1 = stack.pop()
if char == '+':
stack.append(num1 + num2)
elif char == '-':
stack.append(num1 - num2)
elif char == '*':
stack.append(num1 * num2)
elif char == '/':
stack.append(num1 / num2)
return stack[0]
def calculate(expression):
postfix = infix_to_postfix(expression)
result = evaluate_postfix(postfix)
return result
```
您可以调用 `calculate` 函数,并将中缀表达式作为参数传入。函数将返回计算结果。例如:
```python
expression = "3 + 4 * 2 / ( 1 - 5 )"
result = calculate(expression)
print(result) # 输出结果为 1.0
```
请注意,以上代码只支持单个数字的计算,如果需要支持多位数的计算,需要对输入表达式进行解析和拼接。
阅读全文