gpt4 book ai didi

python - python 解析dimacs CNF文件

转载 作者:行者123 更新时间:2023-11-30 23:14:15 30 4
gpt4 key购买 nike

我有一个 DIMACS cnf 格式的文件,我需要将其转换为 SAT 求解器所需的格式。

具体来说,我需要得到:

['c horn? no', 'c forced? no', 'c mixed sat? no', 'c clause length = 3', 'c', 'p cnf 20  91', '4 -18 19 0', '3 18 -5 0', '-5 -8 -15 0', '-20 7 -16 0']

[[4,-18,19,0], [3,18,-5,0],[-5,-8,-15,0],[-20,7,-16,0]]

感谢您的帮助!

最佳答案

作为一种快速破解,您可以简单地使用

in_data = ['c horn? no', 'c forced? no', 'c mixed sat? no', 'c clause length = 3', 'c', 'p cnf 20  91', '4 -18 19 0', '3 18 -5 0', '-5 -8 -15 0', '-20 7 -16 0']
out_data = [[int(n) for n in line.split()] for line in in_data if line[0] not in ('c', 'p')]
print(out_data)

将输出

[[4, -18, 19, 0], [3, 18, -5, 0], [-5, -8, -15, 0], [-20, 7, -16, 0]]

但是,您可能想使用类似的东西

out_data = [[int(n) for n in line.split() if n != '0'] for line in in_data if line[0] not in ('c', 'p')]

而是从子句中删除终止零:

[[4, -18, 19], [3, 18, -5], [-5, -8, -15], [-20, 7, -16]]

但是真正的 dimacs 解析器实际上应该使用终止零,而不是假设每行一个子句。所以这是一个合适的 dimacs 解析器:

in_data = ['c horn? no', 'c forced? no', 'c mixed sat? no', 'c clause length = 3', 'c', 'p cnf 20  91', '4 -18 19 0', '3 18 -5 0', '-5 -8 -15 0', '-20 7 -16 0']

cnf = list()
cnf.append(list())
maxvar = 0

for line in in_data:
tokens = line.split()
if len(tokens) != 0 and tokens[0] not in ("p", "c"):
for tok in tokens:
lit = int(tok)
maxvar = max(maxvar, abs(lit))
if lit == 0:
cnf.append(list())
else:
cnf[-1].append(lit)

assert len(cnf[-1]) == 0
cnf.pop()

print(cnf)
print(maxvar)

关于python - python 解析dimacs CNF文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28890268/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com