boolean sat检查我的代码

时间:2014-04-04 07:48:34

标签: python algorithm boolean satisfiability

我的代码错误答案

n是变量的数量 和formula是包含子句的列表

给定一个SAT实例,其中'n'个变量和子句在列表'公式'中编码,   如果实例是可满足的,则返回'可满足',并且'不可满足'   除此以外。 'formula'的每个元素代表一个子句,并且是一个列表   整数i表示文字Xi存在于整数中的整数   子句和整数-i表示文字~Xi存在于   条款。例如,用列表表示子句“X1 v~X11 v X7”   [1,-11,7]。

import itertools
n = 4 
formula = [[1, -2, 3], [-1, 3], [-3], [2, 3]]


booleanValues = [True,False] * n

allorderings = set(itertools.permutations(booleanValues, n)) #create possible combinations of variables that can check if formula is satisfiable or not

print(allorderings)

for potential in allorderings:
    l = [] #boolean value for each variable / different combination for each iteration
    for i in potential:
        l.append(i)
    #possible = [False]*n
    aclause = []
    for clause in formula:
        something = []
        #clause is [1,2,3]
        for item in clause:
            if item > 0:
                something.append(l[item-1]) 
            else:
                item = item * -1
                x = l[item-1]
                if x == True:
                    x = False
                else:
                    x = True
                something.append(x)
        counter = 0
        cal = False
        for thingsinclause in something:
            if counter == 0:
                cal = thingsinclause
                counter = counter + 1
            else:
                cal = cal and thingsinclause
                counter = counter + 1

        aclause.append(cal)

    counter2 = 0
    formcheck = False
    for checkformula in aclause:
        if counter2 == 0:
            formcheck = checkformula
            counter2 = counter2 + 1
        else:
            formcheck = formcheck or checkformula
    print("this combination works", checkformula)

1 个答案:

答案 0 :(得分:0)

以下是更正后的版本:

import itertools
n = 4 
formula = [[1, -2, 3], [-1, 3], [-3], [2, 3]]

allorderings = itertools.product ([False, True], repeat = n)

for potential in allorderings:
    print ("Initial values:", potential)
    allclauses = []
    for clause in formula:
        curclause = []
        for item in clause:
            x = potential[abs (item) - 1]
            curclause.append (x if item > 0 else not x)
        cal = any (curclause)
        allclauses.append (cal)
    print ("Clauses:", allclauses)
    formcheck = all (allclauses)
    print ("This combination works:", formcheck)

要考虑的要点:

  1. 您可以使用anyall,而不是引入一些复杂的 - 也是错误的 - 逻辑来查找连接和析取。那更干净,更不容易出错。

  2. 要循环的自然对象是itertools.product([False, True], repeat = n),即可能的布尔值的集[False, True]提升到n的幂。换句话说,n的{​​{1}}副本Cartesian productHere是itertools.product的文档。

  3. 我介绍了更多的输出,看看情况如何。这是我用Python3得到的输出(Python2添加括号但打印基本相同):


  4. [False, True]