Skip to content

Instantly share code, notes, and snippets.

@Lipen
Created August 18, 2020 15:03
Show Gist options
  • Save Lipen/6fd2074966822cf9630ffc8707351ffa to your computer and use it in GitHub Desktop.
Save Lipen/6fd2074966822cf9630ffc8707351ffa to your computer and use it in GitHub Desktop.
Sample problem solving using PySAT
from pysat.formula import CNF, IDPool
from pysat.solvers import Minisat22
n, k = map(int, input().split())
cnf = CNF()
vpool = IDPool(start_from=1)
def bit(i):
return vpool.id(f'v@{i}')
for i in range(1, n + 1):
if i <= k:
cnf.append([bit(i)])
else:
cnf.append([-bit(i)])
# print(f'cnf = {cnf.clauses}')
with Minisat22(bootstrap_with=cnf.clauses) as s:
if s.solve():
print('SAT')
answer = ''.join(map(lambda x: '0' if x < 0 else '1', s.get_model()))
print(answer)
else:
print('UNSAT')
assert answer == '1' * k + '0' * (n - k)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment