Python 嵌套列表与递归问题
我正在尝试处理一个用嵌套列表和字符串表示的第一阶逻辑公式,目标是将其转换为析取范式。
比如说,像这样的结构:['&', ['|', 'a', 'b'], ['|', 'c', 'd']]
要变成:
['|' ['&', ['&', 'a', 'c'], ['&', 'b', 'c']], ['&', ['&', 'a', 'd'], ['&', 'b', 'd']]]
这里的 | 代表“或”,而 & 代表“和”。
目前我使用的是递归的方法,这个方法会多次遍历公式,直到找不到嵌套的“或”符号在“和”的列表参数里面。
这是我的实现,performDNF(form) 是入口点。现在它只对公式进行了一次遍历,但接下来的循环检查函数发现“和”里面没有“或”,于是就结束了。谁能帮帮我,这让我快疯了。
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
2 个回答
抱歉,我没有认真去理解你的解决方案。我觉得它读起来太复杂了,可能方法也太繁琐了。
如果你有一个DNF(析取范式),你只需要找到所有原子的组合,从每个子列表中选一个。这其实就是在解决这个问题……从每个“或”子句中选一个原子,然后把这些原子用“与”结合起来。
所有这些可能的“与”子句的“或”组合就能得到你想要的结果,对吧?
好的,这里有一个看起来有效的解决方案。
我不太理解你的代码,也没听说过DNF,所以我开始多研究了一下这个问题。
这篇关于DNF的维基百科页面对我很有帮助,里面有描述DNF的语法。
基于这些信息,我写了一些简单的递归函数,我认为这些函数可以正确识别你需要的DNF格式。我的代码中还包含了一些简单的测试案例。
然后我意识到,你的数据表示是二叉树的形式,这让应用德摩根定律来简化“非”情况变得相对简单。我写了一个叫negate()
的函数,它可以递归地进行取反,其他部分也就顺利完成了。
我已经包含了测试案例,似乎运行得不错。
我没有进一步的计划去完善这个。如果有人发现了bug,请提供一个测试案例,我会看看。
这段代码应该可以在任何Python 2.4或更新的版本上运行。你甚至可以通过把frozenset替换成简单的字符列表,来移植到更旧的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
循环扣分,所以你应该有动力去尝试这个。我希望你在这个过程中能玩得开心,也希望你能从我的代码中学到一些有用的东西。