A formula in clause form is a list of clauses that must all be true; each clause is an "or" of letters and negated letters. Deciding whether any assignment satisfies such a formula is the famous SAT problem, and for small n you can simply try every row.
What to build
A program that counts the assignments of x1 to xn that make every clause true.
Requirements
- Read n and m, then m lines, each a clause: a list of non-zero whole numbers where k means x_k and -k means not x_k.
- Try the assignments in the order given by product([True, False], repeat=n), so the first is all true.
- Print
satisfying: Kwith the number of assignments that make every clause true. - Print
first:and the first satisfying assignment as n letters T or F (x1 first), orfirst: none.
Input
The first line has n and m. Each of the next m lines is one clause.
Output
Two lines.
Constraints
1 ≤ n ≤ 10; 1 ≤ m ≤ 20; each clause has 1 to 5 literals.
Example
Input:
2 1
1 -2
Output:
satisfying: 3
first: TT
Why it works
A truth table over n letters has 2 to the power n rows, so for n up to 10 trying them all is fast. A clause is an any() over its literals and the whole formula is an all() over its clauses, which is exactly the conjunction of disjunctions that the problem describes.
Examples
2 1 1 -2
satisfying: 3 first: TT
3 2 1 2 -1 3
satisfying: 4 first: TTT
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Number the variables 1 to n. A clause is a list of numbers: 3 means x3 and -3 means not x3.
Hint 2
A clause is true when any one of its literals is true; the formula is true when all clauses are true.
Hint 3
Loop over product([True, False], repeat=n) and keep the count and the first assignment that works.
Solution
Show one correct solution (try it yourself first)
from itertools import product
n, m = map(int, input().split())
clauses = [list(map(int, input().split())) for _ in range(m)]
count = 0
first = None
for row in product([True, False], repeat=n):
ok = all(any(row[abs(k) - 1] == (k > 0) for k in clause) for clause in clauses)
if ok:
count += 1
if first is None:
first = "".join("T" if v else "F" for v in row)
print("satisfying:", count)
print("first:", first if first else "none")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step