您可以让最外层的list表示“OR all direct entries”,然后在OR和and direct条目之间交换嵌套列表的含义。如果从最外层开始计算嵌套级别为1,则奇数嵌套级别中的项应为OR'd,偶数嵌套级别中的项应为and'd。在
所以ABC+DE(FG+IH)
变成[[A,B,C],[D,E,[[F,G],[I,H]]]]
下面是一些Python代码:
它从列表形式返回一个表达式:def to_bool(lst, depth=0, or_them=True):
if type(lst) == str:
return lst
else:
partial = ( '+' if or_them else ''
).join( to_bool(x, depth+1, not or_them) for x in lst)
if or_them and depth > 0:
# Mixture of variables and sublists so parenthesize
return '(' + partial + ')'
else:
return partial
def main():
A,B,C,D,E,F,G,H,I = 'ABCDEFGHI'
e = [[A,B,C],[D,E,[[F,G],[I,H]]]]
print('The list form of the boolean expression:', e)
print('The boolean expression:', to_bool(e))
if __name__ == '__main__':
main()
其输出:
^{pr2}$