UNB/ CS/ David Bremner/ teaching/ cs3383/ lectures/ 50.1-demos/ two sat.py
#!/usr/bin/env python3
from unit_prop import UnitProp

def reduce(clauses,literal):
  out=[]
  for C in clauses:
    if not literal in C:
      new=[z for z in C if z != -1*literal]
      out.append(new)
  return out

def expand(clauses):
  j = clauses[0][0]
  return [reduce(clauses,j),
          reduce(clauses,-j)]

def test(clauses):
    if (len(clauses)) == 0:
        return True
    for clause in clauses:
        if len(clause)==0:
            return False
    return None

def two_sat(clauses):
  if len(clauses) == 0:
      return True
  j = clauses[0][0]
  R0 = UnitProp(reduce(clauses,-j))
  R1 = UnitProp(reduce(clauses,j))
  if True in [ R0, R1 ]: return True
  if R0 == False and R1 == False: return False
  if R0 == False:
      return two_sat(R1)
  else:
      return two_sat(R0)

if __name__ == "__main__":
    print(two_sat([ [1,3], [-1,2] ,[-1,3] ]))
    print(two_sat([ [1], [-1,2], [-2] ]))
    print(two_sat([ [1,2], [1, 3], [-1, 4], [-4, 5], [-4, 6] ]))
    print(two_sat([ [-1,-2], [-1, -3], [1, -4], [4, -5], [4, 6] ]))