用python编写一个函数f(s: str) -> str ,判断一个合式公式s是永真式、永假式还是可满足式。 (在s中,命题变元最多有p,q,r三个,仅包含与、或、非三种运算,用and, or, not来表示)函数要求:读入满足上述要求的代表s的非空字符串,如果是永真式则返回"永真式",如果不是永真式但是可满足式则返回“可满足式",如果是永假式返回“永假式”(不要返回引号)
时间: 2023-05-27 08:05:30 浏览: 105
思路:
1. 将输入的字符串转换为逆波兰表达式;
2. 根据逆波兰表达式计算表达式的值;
3. 如果表达式的值为1,则为永真式;
4. 如果表达式的值为0,则为永假式;
5. 如果表达式的值不为0也不为1,则为可满足式。
代码实现如下:
```python
def f(s: str) -> str:
def is_operator(c):
return c in ['and', 'or', 'not']
def priority(c):
if c == 'not':
return 3
elif c == 'and':
return 2
elif c == 'or':
return 1
else:
return 0
def to_rpn(s):
stack = []
rpn = []
for c in s.split():
if c == '(':
stack.append(c)
elif c == ')':
while stack and stack[-1] != '(':
rpn.append(stack.pop())
stack.pop()
elif is_operator(c):
while stack and is_operator(stack[-1]) and priority(stack[-1]) >= priority(c):
rpn.append(stack.pop())
stack.append(c)
else:
rpn.append(c)
while stack:
rpn.append(stack.pop())
return rpn
def eval_rpn(rpn, values):
stack = []
for c in rpn:
if is_operator(c):
if c == 'not':
stack.append(not stack.pop())
elif c == 'and':
stack.append(stack.pop() and stack.pop())
elif c == 'or':
stack.append(stack.pop() or stack.pop())
else:
stack.append(values[c])
return stack.pop()
variables = set(['p', 'q', 'r'])
values = {}
for v in variables:
values[v] = False
for i in range(2 ** len(variables)):
for j, v in enumerate(variables):
values[v] = bool(i & (1 << j))
rpn = to_rpn(s)
if not eval_rpn(rpn, values):
return '可满足式'
if eval_rpn(to_rpn(s), values):
return '永真式'
else:
return '永假式'
```
使用示例:
```python
>>> f('not p or q')
'可满足式'
>>> f('not (p and q)')
'永真式'
>>> f('p and q or not r')
'可满足式'
>>> f('not p and not q')
'永假式'
```
阅读全文