布尔sat检查我的货到付款

2024-10-02 20:31:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码得到了一个错误的答案

n是变量的数目 公式是一个包含子句的列表

给定一个SAT实例,其中包含以列表“formula”编码的“n”变量和子句, 如果实例可满足,则返回“satisfailable”;如果实例可满足,则返回“unsatisfailable” 否则。“formula”的每个元素表示一个子句,并且是 整数,其中整数i表示文本Xi存在于 子句和整数-i表示文本~Xi存在于 条款。例如,子句“x1v~x11vx7”用列表表示 [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)

Tags: infalseforifcounteritemelsesomething
1条回答
网友
1楼 · 发布于 2024-10-02 20:31:46

以下是更正版本:

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. 您可以使用^{}^{},而不是引入一些复杂且错误的逻辑来查找连词和析取。这样更干净,更不容易出虫子。

  2. 要循环的自然对象是itertools.product([False, True], repeat = n),也就是说,可能的布尔值集[False, True]的幂次方。换句话说,nCartesian product[False, True]的拷贝。Here是的文档itertools.product.

  3. 我引入了更多的输出来了解情况。这是我用Python3得到的输出(Python2添加了括号,但打印的内容基本相同):


^{pr2}$

相关问题 更多 >