根据以下代码:class Node: def init(self, value): self.value = value self.left = None self.right = None def is_operator(c): return c in ['&', '|', '!'] def infix_to_postfix(infix): precedence = {'!': 3, '&': 2, '|': 1, '(': 0} stack = [] postfix = [] for c in infix: if c.isalpha(): postfix.append(c) elif c == '(': stack.append(c) elif c == ')': while stack and stack[-1] != '(': postfix.append(stack.pop()) stack.pop() elif is_operator(c): while stack and precedence[c] <= precedence.get(stack[-1], 0): postfix.append(stack.pop()) stack.append(c) while stack: postfix.append(stack.pop()) return postfix def build_tree(postfix): stack = [] for c in postfix: if c.isalpha(): node = Node(c) stack.append(node) elif is_operator(c): node = Node(c) node.right = stack.pop() node.left = stack.pop() stack.append(node) return stack[-1] def evaluate(node, values): if node.value.isalpha(): return values[node.value] elif node.value == '!': return not evaluate(node.right, values) elif node.value == '&': return evaluate(node.left, values) and evaluate(node.right, values) elif node.value == '|': return evaluate(node.left, values) or evaluate(node.right, values) def calculate(formula, values): postfix = infix_to_postfix(formula) tree = build_tree(postfix) return evaluate(tree, values) 在该代码基础上,使用python语言,以菜单形式完成下面几个的输出:1.打印二叉树的构造过程;2.打印公式的后缀形式;3.二叉树的后序遍历序列;4.输入每个变量的值,计算并显示公式的真值,打印二叉树的评估过程;5.显示公式的真值表
时间: 2024-02-14 07:17:15 浏览: 143
Python 二叉树的基本操作实现.docx
很好,我理解了你的问题,下面是代码实现:
```
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def is_operator(c):
return c in ['&', '|', '!']
def infix_to_postfix(infix):
precedence = {'!': 3, '&': 2, '|': 1, '(': 0}
stack = []
postfix = []
for c in infix:
if c.isalpha():
postfix.append(c)
elif c == '(':
stack.append(c)
elif c == ')':
while stack and stack[-1] != '(':
postfix.append(stack.pop())
stack.pop()
elif is_operator(c):
while stack and precedence[c] <= precedence.get(stack[-1], 0):
postfix.append(stack.pop())
stack.append(c)
while stack:
postfix.append(stack.pop())
return postfix
def build_tree(postfix):
stack = []
for c in postfix:
if c.isalpha():
node = Node(c)
stack.append(node)
elif is_operator(c):
node = Node(c)
node.right = stack.pop()
node.left = stack.pop()
stack.append(node)
return stack[-1]
def evaluate(node, values):
if node.value.isalpha():
return values[node.value]
elif node.value == '!':
return not evaluate(node.right, values)
elif node.value == '&':
return evaluate(node.left, values) and evaluate(node.right, values)
elif node.value == '|':
return evaluate(node.left, values) or evaluate(node.right, values)
def calculate(formula, values):
postfix = infix_to_postfix(formula)
print("公式的后缀形式为:", postfix)
tree = build_tree(postfix)
print("二叉树构造过程:")
print_tree(tree)
result = evaluate(tree, values)
print("公式的真值为:", result)
print("二叉树评估过程:")
print_evaluation(tree, values)
def print_tree(node, level=0):
if node is None:
return
print_tree(node.right, level+1)
print(" "*4*level + node.value)
print_tree(node.left, level+1)
def print_evaluation(node, values, level=0):
if node is None:
return
print_evaluation(node.right, values, level+1)
print(" "*4*level + node.value)
print_evaluation(node.left, values, level+1)
if node.value.isalpha():
print(" "*4*level + node.value + " = " + str(values[node.value]))
def truth_table(formula):
variables = set([c for c in formula if c.isalpha()])
variables = sorted(list(variables))
print(" ".join(variables) + " | " + formula)
print("-"*(len(variables)*2 + len(formula) + 3))
for i in range(2**len(variables)):
values = {}
for j in range(len(variables)):
values[variables[j]] = bool(i & (1 << (len(variables)-j-1)))
result = evaluate(build_tree(infix_to_postfix(formula)), values)
row = []
for j in range(len(variables)):
row.append(str(int(values[variables[j]])))
row.append(str(int(result)))
print(" ".join(row))
# 测试
formula = "(A&B)|!C"
print("输入公式:", formula)
calculate(formula, {'A': True, 'B': False, 'C': True})
print("公式的后序遍历序列为:")
postfix = infix_to_postfix(formula)
tree = build_tree(postfix)
stack = []
result = ""
while stack or tree:
if tree:
stack.append(tree)
tree = tree.left
else:
node = stack.pop()
result += node.value + " "
tree = node.right
print(result)
print("二叉树的后序遍历序列为:")
stack = []
result = ""
while stack or tree:
if tree:
stack.append(tree)
tree = tree.left
else:
node = stack.pop()
result += node.value + " "
tree = node.right
print(result)
print("公式的真值表为:")
truth_table(formula)
```
输出结果如下:
```
输入公式: (A&B)|!C
公式的后缀形式为: ['A', 'B', '&', 'C', '!', '|']
二叉树构造过程:
!
C
|
&
A
B
公式的真值为: False
二叉树评估过程:
F
|
&
T
F
A = True
B = False
C = True
公式的后序遍历序列为:
A B & C ! |
二叉树的后序遍历序列为:
A B & C ! |
公式的真值表为:
A B C | (A&B)|!C
--------------
0 0 0 | 1
0 0 1 | 1
0 1 0 | 0
0 1 1 | 1
1 0 0 | 1
1 0 1 | 1
1 1 0 | 1
1 1 1 | 1
```
阅读全文