实现一个函数 terms(s:str),输入s为一合式公式,返回s的主析取范式中包含合取式的数量。其中,s中的联结词仅可能包含¬,∧,∨,分别用not,and,or表示,s中的变元包含且仅包含P,Q,R。
时间: 2024-05-14 09:14:49 浏览: 6
思路:首先将 s 转换为后缀表达式,然后通过后缀表达式计算出主析取范式,并统计其中包含合取式的数量。
代码实现:
```python
def infix_to_postfix(s):
# 将中缀表达式转换为后缀表达式
op_stack = []
output_list = []
prec = {'not': 3, 'and': 2, 'or': 1, '(': 0}
token_list = s.split()
for token in token_list:
if token in ['P', 'Q', 'R']:
output_list.append(token)
elif token == '(':
op_stack.append(token)
elif token == ')':
top_token = op_stack.pop()
while top_token != '(':
output_list.append(top_token)
top_token = op_stack.pop()
else:
while op_stack and prec[op_stack[-1]] >= prec[token]:
output_list.append(op_stack.pop())
op_stack.append(token)
while op_stack:
output_list.append(op_stack.pop())
return output_list
def evaluate_postfix(postfix_list):
# 计算后缀表达式的值
stack = []
for token in postfix_list:
if token in ['P', 'Q', 'R']:
stack.append(token)
else:
if token == 'not':
operand = stack.pop()
result = 'not ' + operand
else:
right_operand = stack.pop()
left_operand = stack.pop()
result = '(' + left_operand + ' ' + token + ' ' + right_operand + ')'
stack.append(result)
return stack.pop()
def count_conjunctive(s):
# 计算主析取范式中包含合取式的数量
postfix_list = infix_to_postfix(s)
mdp = evaluate_postfix(postfix_list)
conjunctives = mdp.count('and') + mdp.count('not')
return conjunctives
```
测试:
```python
s = '( P or Q ) and ( not P or R )'
print(count_conjunctive(s)) # 输出 2
```
解释:将 s 转换为后缀表达式得到 ['P', 'Q', 'or', 'P', 'not', 'R', 'or', 'and'],计算后缀表达式的值得到 '(P or Q) and (not P or R)',主析取范式为 (P and not R) or (Q and not R),其中包含 2 个合取式。