我正在尝试处理在python中表示为嵌套列表和字符串的一阶逻辑公式,以便它处于析取范式,
即['&',['|','a','b'],['|','c','d']]
变成
[ '|' ['&',['&','a','c'],['&','b','c']],['&',['&',' a','d'],['&','b','d']]]
其中|是'或'和&是'和'。
目前我正在使用递归实现,该实现对公式进行多次传递,直到它无法在'ands'的列表参数中找到任何嵌套的'或'符号。
这是我的实现,performDNF(表单)是入口点。现在它只对公式执行一次传递,但是while循环检查函数在'&'中找不到'|'并终止,帮助任何人让我发疯。
def dnfDistributivity(self, form):
if isinstance(form, type([])):
if len(form) == 3:
if form[0] == '&':
if form[1][0] == '|':
form = ['|', ['&', form[2], form[1][1]], ['&', form[2], form[1][2]]]
elif form[2][0] == '|':
form = ['|', ['&', form[1], form[2][1]], ['&', form[1], form[2][2]]]
form[1] = self.dnfDistributivity(form[1])
form[2] = self.dnfDistributivity(form[2])
elif len(form) == 2:
form[1] = self.dnfDistributivity(form[1])
return form
def checkDistributivity(self, form, result = 0):
if isinstance(form, type([])):
if len(form) == 3:
if form[0] == '&':
print "found &"
if isinstance(form[1], type([])):
if form[1][0] == '|':
return 1
elif isinstance(form[2], type([])):
if form[2][0] == '|':
return 1
else:
result = self.checkDistributivity(form[1], result)
print result
if result != 1:
result = self.checkDistributivity(form[2], result)
print result
elif len(form) == 2:
result = self.checkDistributivity(form[1], result)
print result
return result
def performDNF(self, form):
while self.checkDistributivity(form):
form = self.dnfDistributivity(self.dnfDistributivity(form))
return form
答案 0 :(得分:1)
好的,这是一个似乎有用的实际解决方案。
我不明白你的代码,我没有听说过DNF,所以我开始研究这个问题了。
Wikipedia page on DNF非常有帮助。它包括描述DNF的语法。
基于此,我编写了一组简单的递归函数,我认为它们能够以您需要的格式正确识别DNF。我的代码包含一些简单的测试用例。
然后我意识到数据表示的二叉树性质使得通过编写一个名为negate()
的递归否定的函数来应用DeMorgan定律来简化'not'的情况变得相对简单,其余的则归结为的地方。
我已经包含了测试用例。它似乎有效。
我没有进一步的计划来解决这个问题。如果有人发现了错误,请提供一个测试用例,我会看一下。
此代码应在任何Python 2.4或更高版本上运行。你甚至可以通过用一个简单的字符列表替换freezeset来将它移植到旧的Python版本。我使用Python 3.x进行了测试,发现异常语法已经更改,因此如果要在Python 3下运行它,则需要更改raise
行;所有重要的部分都有效。
在这个问题中,你没有提到你用not
的字符;如果您对&
使用and
而|
使用or
,我认为您可能会!
使用not
并相应地编写代码。这是让您对代码感到困惑的事情之一:您是否曾期望在输入中找到not
?
我在这方面有一些乐趣。它并不像数独之谜那样毫无意义。
import sys
ch_and = '&'
ch_not = '!'
ch_or = '|'
def echo(*args):
# like print() in Python 3 but works in 2.x or in 3
sys.stdout.write(" ".join(str(x) for x in args) + "\n")
try:
symbols = frozenset([ch_and, ch_not, ch_or])
except NameError:
raise Exception, "sorry, your Python is too old for this code"
try:
__str_type = basestring
except NameError:
__str_type = str
def is_symbol(x):
if not isinstance(x, __str_type) or len(x) == 0:
return False
return x[0] in symbols
def is_and(x):
if not isinstance(x, __str_type) or len(x) == 0:
return False
return x[0] == ch_and
def is_or(x):
if not isinstance(x, __str_type) or len(x) == 0:
return False
return x[0] == ch_or
def is_not(x):
if not isinstance(x, __str_type) or len(x) == 0:
return False
return x[0] == ch_not
def is_literal_char(x):
if not isinstance(x, __str_type) or len(x) == 0:
return False
return x[0] not in symbols
def is_list(x, n):
return isinstance(x, list) and len(x) == n
def is_literal(x):
"""\
True if x is a literal char, or a 'not' followed by a literal char."""
if is_literal_char(x):
return True
return is_list(x, 2) and is_not(x[0]) and is_literal_char(x[1])
def is_conjunct(x):
"""\
True if x is a literal, or 'and' followed by two conjuctions."""
if is_literal(x):
return True
return (is_list(x, 3) and
is_and(x[0]) and is_conjunct(x[1]) and is_conjunct(x[2]))
def is_disjunct(x):
"""\
True if x is a conjunction, or 'or' followed by two disjuctions."""
if is_conjunct(x):
return True
return (is_list(x, 3) and
is_or(x[0]) and is_disjunct(x[1]) and is_disjunct(x[2]))
def is_dnf(x):
return is_disjunct(x)
def is_wf(x):
"""returns True if x is a well-formed list"""
if is_literal(x):
return True
elif not isinstance(x, list):
raise TypeError, "only lists allowed"
elif len(x) == 2 and is_not(x[0]) and is_wf(x[1]):
return True
else:
return (is_list(x, 3) and (is_and(x[0]) or is_or(x[0])) and
is_wf(x[1]) and is_wf(x[2]))
def negate(x):
# trivial: negate a returns !a
if is_literal_char(x):
return [ch_not, x]
# trivial: negate !a returns a
if is_list(x, 2) and is_not(x[0]):
return x[1]
# DeMorgan's law: negate (a && b) returns (!a || !b)
if is_list(x, 3) and is_and(x[0]):
return [ch_or, negate(x[1]), negate(x[2])]
# DeMorgan's law: negate (a || b) returns (!a && !b)
if is_list(x, 3) and is_or(x[0]):
return [ch_and, negate(x[1]), negate(x[2])]
raise ValueError, "negate() only works on well-formed values."
def __rewrite(x):
# handle all dnf, which includes simple literals.
if is_dnf(x):
# basis case. no work to do, return unchanged.
return x
if len(x) == 2 and is_not(x[0]):
x1 = x[1]
if is_list(x1, 2) and is_not(x1[0]):
# double negative! throw away the 'not' 'not' and keep rewriting.
return __rewrite(x1[1])
assert is_list(x1, 3)
# handle non-inner 'not'
return __rewrite(negate(x1))
# handle 'and' with 'or' inside it
assert is_list(x, 3) and is_and(x[0]) or is_or(x[0])
if len(x) == 3 and is_and(x[0]):
x1, x2 = x[1], x[2]
if ((is_list(x1, 3) and is_or(x1[0])) and
(is_list(x2, 3) and is_or(x2[0]))):
# (a || b) && (c || d) -- (a && c) || (b && c) || (a && d) || (b && d)
lst_ac = [ch_and, x1[1], x2[1]]
lst_bc = [ch_and, x1[2], x2[1]]
lst_ad = [ch_and, x1[1], x2[2]]
lst_bd = [ch_and, x1[2], x2[2]]
new_x = [ch_or, [ch_or, lst_ac, lst_bc], [ch_or, lst_ad, lst_bd]]
return __rewrite(new_x)
if (is_list(x2, 3) and is_or(x2[0])):
# a && (b || c) -- (a && b) || (a && c)
lst_ab = [ch_and, x1, x2[1]]
lst_ac = [ch_and, x1, x2[2]]
new_x = [ch_or, lst_ab, lst_ac]
return __rewrite(new_x)
if (is_list(x1, 3) and is_or(x1[0])):
# (a || b) && c -- (a && c) || (b && c)
lst_ac = [ch_and, x1[1], x2]
lst_bc = [ch_and, x1[2], x2]
new_x = [ch_or, lst_ac, lst_bc]
return __rewrite(new_x)
return [x[0], __rewrite(x[1]), __rewrite(x[2])]
#return x
def rewrite(x):
if not is_wf(x):
raise ValueError, "can only rewrite well-formed lists"
while not is_dnf(x):
x = __rewrite(x)
return x
#### self-test code ####
__failed = False
__verbose = True
def test_not_wf(x):
global __failed
if is_wf(x):
echo("is_wf() returned True for:", x)
__failed = True
def test_dnf(x):
global __failed
if not is_wf(x):
echo("is_wf() returned False for:", x)
__failed = True
elif not is_dnf(x):
echo("is_dnf() returned False for:", x)
__failed = True
def test_not_dnf(x):
global __failed
if not is_wf(x):
echo("is_wf() returned False for:", x)
__failed = True
elif is_dnf(x):
echo("is_dnf() returned True for:", x)
__failed = True
else:
xr = rewrite(x)
if not is_wf(xr):
echo("rewrite produced non-well-formed for:", x)
echo("result was:", xr)
__failed = True
elif not is_dnf(xr):
echo("rewrite failed for:", x)
echo("result was:", xr)
__failed = True
else:
if __verbose:
echo("original:", x)
echo("rewritten:", xr)
echo()
def self_test():
a, b, c, d = 'a', 'b', 'c', 'd'
test_dnf(a)
test_dnf(b)
test_dnf(c)
test_dnf(d)
lstna = [ch_not, a]
test_dnf(lstna)
lstnb = [ch_not, b]
test_dnf(lstnb)
lsta = [ch_and, a, b]
test_dnf(lsta)
lsto = [ch_or, a, b]
test_dnf(lsto)
test_dnf([ch_and, lsta, lsta])
test_dnf([ch_or, lsta, lsta])
lstnn = [ch_not, [ch_not, a]]
test_not_dnf(lstnn)
test_not_dnf([ch_and, lstnn, lstnn])
# test 'and'/'or' inside 'not'
test_not_dnf([ch_not, lsta])
test_not_dnf([ch_not, lsto])
# test 'or' inside of 'and'
# a&(b|c) --> (a&b)|(b&c)
test_not_dnf([ch_and, a, [ch_or, b, c]])
# (a|b)&c --> (a&c)|(b&c)
test_not_dnf([ch_and, [ch_or, a, b], c])
# (a|b)&(c|d) --> ((a&c)|(b&c))|((a&d)|(b&d))
test_not_dnf([ch_and, [ch_or, a, b], [ch_or, c, d]])
# a&a&a&(b|c) --> a&a&(a&b|b&c) --> a&(a&a&b|a&b&c) --> (a&a&a&b|a&a&b&c)
test_not_dnf([ch_and, a, [ch_and, a, [ch_and, a, [ch_or, b, c]]]])
if __failed:
echo("one or more tests failed")
self_test()
现在,我很抱歉这样说,但是我想的越多,我想你可能就越想让我为你做功课。所以,我刚刚写了这个代码的改进版本,但我不打算在这里分享它;我会把它作为锻炼给你。在我描述之后,你应该能够轻松地做到这一点。
这是一个可怕的黑客,我有一个while
循环反复调用__rewrite()
。 rewrite()
函数应该只需调用__rewrite()
即可重写树结构。只需进行一些简单的更改,您就可以摆脱while
循环;我做了,并测试了它,它的工作原理。你希望__rewrite()
向下走树,然后在回来的路上重写东西,它将在一次通过。如果列表格式不正确,您还可以修改__rewrite()
以返回错误,并取消对is_wf()
的调用;这也很容易。
我怀疑你的老师会为while
循环停靠你的积分,所以你应该有动力尝试这个。我希望你能玩得很开心,我希望你能从我的代码中学到一些有用的东西。
答案 1 :(得分:0)
对不起,我并没有真正理解你的解决方案。我认为阅读起来太难了,可能这种方法太麻烦了。
如果你有一个DNF,你需要做的就是找到原子的所有组合,从每个子列表中取出一个。这几乎归结为this问题...来自每个OR子条款,你需要取一个原子,并将所有这些与AND结合起来。
所有可能的AND子句的OR组合产生您想要的结果。正确?