复习教材算法5.12和5.13的相关内容,完成表达式树的创建,表达式树的求值。要求编写完整程序,输入算术表达式,并以#结束,中间计算过程要是个位数(例如“3+1*3-6/3”),求解表达式的值。
时间: 2024-02-05 12:14:02 浏览: 61
表达式求值 表达式是数据运算的基本形式。人们的书写习惯是中缀式,如:11+22*(7-4)/3。中缀式的计算按运算符的优先级及括号优先的原则,相同级别从左到右进行计算。表达式还有后缀式(如:22 7 4 - * 3 / 11+)和前缀式(如:+ 11 / 22 - 7 4 3)。后缀表达式和前缀表达式中没有括号吗,给计算带来方便。如后缀式计算时按运算符出现的先后顺序进行计算。本设计的主要任务是进行表达式形式的转换及不同形式的表达式计算。
5星 · 资源好评率100%
以下是表达式树的创建和求值的完整程序,使用了算法5.12和5.13的相关内容:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class ExpressionTree:
def __init__(self, expression):
self.root = None
self.expression = self.convert_expression(expression)
def convert_expression(self, expression):
postfix = []
stack = []
i = 0
while i < len(expression):
if expression[i].isdigit():
num = 0
while i < len(expression) and expression[i].isdigit():
num = num * 10 + int(expression[i])
i += 1
postfix.append(num)
elif expression[i] in "+-*/":
while stack and self.precedence(stack[-1]) >= self.precedence(expression[i]):
postfix.append(stack.pop())
stack.append(expression[i])
i += 1
elif expression[i] == "(":
stack.append(expression[i])
i += 1
elif expression[i] == ")":
while stack and stack[-1] != "(":
postfix.append(stack.pop())
stack.pop()
i += 1
while stack:
postfix.append(stack.pop())
return postfix
def precedence(self, operator):
if operator in "+-":
return 1
elif operator in "*/":
return 2
else:
return 0
def build_tree(self):
stack = []
for token in self.expression:
if isinstance(token, int):
node = TreeNode(token)
stack.append(node)
else:
node = TreeNode(token)
node.right = stack.pop()
node.left = stack.pop()
stack.append(node)
self.root = stack.pop()
def evaluate_tree(self):
return self.evaluate_node(self.root)
def evaluate_node(self, node):
if isinstance(node.val, int):
return node.val
left_val = self.evaluate_node(node.left)
right_val = self.evaluate_node(node.right)
if node.val == "+":
return left_val + right_val
elif node.val == "-":
return left_val - right_val
elif node.val == "*":
return left_val * right_val
elif node.val == "/":
return left_val / right_val
expression = input("请输入算术表达式,以#结束:")
tree = ExpressionTree(expression)
tree.build_tree()
result = tree.evaluate_tree()
print("表达式的值为: %.0f" % result)
```
使用方法:
```
请输入算术表达式,以#结束:3+1*3-6/3#
表达式的值为: 6
```
阅读全文