Skip to content

Instantly share code, notes, and snippets.

@dniku
Last active December 18, 2015 20:38
Show Gist options
  • Save dniku/5841078 to your computer and use it in GitHub Desktop.
Save dniku/5841078 to your computer and use it in GitHub Desktop.
to_bool = {'T': True, 'F': False}
def matches(what, whom):
return (whom == '?') or (what == to_bool[whom])
def simplify(answers):
if len(answers) > 1:
return '?'
return ['F', 'T'][answers.pop()]
def solve(line):
allowed = [(True, True), (True, False), (False, True), (False, False)]
# Reading characters
allowed = [(a, b) for a, b in allowed if matches(a, line[0]) and matches(b, line[1])]
# Checking AND, OR, XOR, IMP
allowed = [(a, b) for a, b in allowed if matches(a and b, line[2])]
allowed = [(a, b) for a, b in allowed if matches(a or b, line[3])]
allowed = [(a, b) for a, b in allowed if matches(a != b, line[4])]
allowed = [(a, b) for a, b in allowed if matches(not a or b, line[5])]
# No such combination of inputs
if not allowed:
return 'ERROR'
# Combining answers
A = simplify({a for a, b in allowed})
B = simplify({b for a, b in allowed})
AND = simplify({a and b for a, b in allowed})
OR = simplify({a or b for a, b in allowed})
XOR = simplify({a != b for a, b in allowed})
IMP = simplify({not a or b for a, b in allowed})
return A + B + AND + OR + XOR + IMP
with open('bool.in', 'r') as fin:
with open('book.out', 'w') as fout:
fin.next() # skipping n
for line in fin:
print >>fout, solve(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment