python : Apply distributive law to elements in list

标签 python python-2.7

我想在 python2.7 下面做。它适用于 2 个子元素,但我可以有多个子元素。

NOT = "not"
OR = "or"
AND  = "and"

def convertMain(prop) :

    if isinstance(prop, str) : 
        answer = prop
    else :
        op = prop[0]
        #tree1 =  convertIntoCNF(prop[1])
        #tree2 =  convertIntoCNF(prop[2])
        """{ assert: tree1 and tree2  are in  cnf }"""
        if op == AND :            
            answer = [AND] + [convertIntoCNF(item) for item in prop[1:]]
        else : # op == OR
            if (len(prop) == 3) :
                tree1 =  convertIntoCNF(prop[1])
                tree2 =  convertIntoCNF(prop[2])

                answer = distOr2(tree1, tree2)

    return answer

def distOr2(p1,p2):

    if isinstance(p1, list) and p1[0] == AND :
        #{ assert:  p1 = P11 & P12 }
        answer = [AND, distOr2(p1[1],p2), distOr2(p1[2],p2)]
    elif  isinstance(p2, list) and p2[0] == AND :
        #{ assert:  p2 = P21 & P22 }
        answer = [AND, distOr2(p1,p2[1]), distOr2(p1,p2[2])]
    else :
        #{ assert: since  p1 and p2 are both in cnf, then both are disjunctive clauses, which can be appended }
        answer = [OR, p1, p2]
    return answer

以上代码适用于以下情况:

 Input  : ['and', ['or', ['and', '-P', 'Q'], 'R'], ['or', '-P', '-R']]
 Output : ['and', ['and', ['or', '-P', 'R'], ['or', 'Q', 'R']], ['or', '-P', '-R']]

解释:

 Input is expression ((-P V Q) V R) ^ (-P V -R))
 Output is expression  ((-P V R) ^ (Q V R)) ^ (-P V -R)

我想让这个适用于任意数量的子元素,如下例所示,“S”是输入中的第三个元素,因此应在输出中添加 ['or', 'S', 'R']:

 Input  : ['and', ['or', ['and', '-P', 'Q', 'S'], 'R'], ['or', '-P', '-R']]
 Output : ['and', ['and', ['or', '-P', 'R'], ['or', 'Q', 'R'], ['or', 'S', 'R']], ['or', '-P', '-R']]

谢谢。

最佳答案

您可以创建一个方法,以递归方式将具有两个以上子元素的任何内容转换为每个列表都有两个子元素的形式(即每个逻辑连接词只有 2 个参数)。例如:

def makeBinary(prop):
    if isinstance(prop, str):
        return prop
    elif len(prop) == 3:
        return [prop[0], makeBinary(prop[1]), makeBinary(prop[2])]
    else:
        return [prop[0], makeBinary(prop[1]), makeBinary([prop[0]] + prop[2:])]

然后您可以在任何命题上调用它,然后再通过您已有的代码运行它,并且您的代码可以安全地假设连接词不会有超过两个参数。

关于 python : Apply distributive law to elements in list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29189355/

相关文章:

python - 在 pyOpenGL 中对齐各个对象以创建更大的聚合对象

python - 如何创建多个图形而不显示它们,直到调用 plt.show ?

python - 在 MVC 模式框架中,屏幕抓取模块位于何处?

python - 从 pandas df 中的列创建二元组

python - 将 QTextEdit 的内容保存为 *.pdf?

python - 通过 Numpy 中的逻辑索引获取矩阵的网格

python - TypeError : Improper input: N=3 must not exceed M=1, 不确定我的尺寸有什么问题?

python - 如何在 Python 中使用 Selenium 动态生成多个 div

python - 如何使用 Python Decorator 只改变函数的一部分?

python - 我可以完全用 Python 签署 X509 证书吗?