我正在尝试处理在 python 中表示为嵌套列表和字符串的一阶逻辑公式,以便其采用析取范式,
即['&', ['|', 'a', 'b'], ['|', 'c', 'd']]
变成
['|' ['&', ['&', 'a', 'c'], ['&', 'b', 'c']], ['&', ['&', 'a', 'd '], ['&', 'b', 'd']]]
哪里|是“或”,& 是“与”。
目前,我使用递归实现,该实现会对公式进行多次传递,直到在“and”的列表参数内找不到任何嵌套的“or”符号。
这是我的实现,performDNF(form) 是入口点。现在它对公式执行一次传递,但随后 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
最佳答案
好的,这是一个似乎有效的实际解决方案。
我不明白你的代码,而且我也没有听说过 DNF,所以我开始进一步研究这个问题。
Wikipedia page on DNF非常有帮助。它包括描述 DNF 的语法。
基于此,我编写了一组简单的递归函数,我相信它们可以正确识别您需要的格式的 DNF。我的代码包括一些简单的测试用例。
然后我意识到,数据表示的二叉树性质使得应用德摩根定律来简化“非”情况变得相对简单,只需编写一个名为 negate()
的函数来递归求反,其余的就各就各位了。
我已经包含了测试用例。看来有效。
我没有进一步的计划来从事这方面的工作。如果有人发现错误,请提供测试用例,我会查看它。
此代码应在任何 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
循环中扣掉你的分数,所以你应该有动力去尝试这个。我希望您玩得开心,也希望您从我的代码中学到一些有用的东西。
关于Python嵌套列表和递归问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1787576/