practice / envs /argument_check /validators.py
birgermoell's picture
Add Practice generators, indices, verification and documentation
2983a9c verified
Raw History Blame Contribute Delete
5.82 kB
"""Custom checks for Argument Check. Standalone, standard library only.
Every function reads the candidate from the answer, evaluates the formulas of the problem itself
(the formulas arrive in `args` as text) and returns True only if the candidate really has the
property asked for. Nothing is compared with a stored solution. Malformed answers return False.
"""
_LEVEL = {"<->": 1, "->": 2, "|": 3, "&": 4}
_MAX_LEN = 2000
class _Bad(Exception):
pass
def _scan(text):
if not isinstance(text, str): raise _Bad()
toks, i, n = [], 0, len(text)
while i < n:
c = text[i]
if c == " " or c == "\t": i += 1
elif c == "<" and text[i:i + 3] == "<->": toks.append("<->"); i += 3
elif c == "-" and text[i:i + 2] == "->": toks.append("->"); i += 2
elif c in ("~", "&", "|", "(", ")"): toks.append(c); i += 1
elif c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": toks.append(c); i += 1
else: raise _Bad()
return toks
def _read(text):
"""Precedence climbing. Tree nodes: ("atom", A), ("not", x), ("bin", op, x, y)."""
toks = _scan(text)
state = {"i": 0}
def primary():
i = state["i"]
if i >= len(toks): raise _Bad()
t = toks[i]; state["i"] = i + 1
if t == "~": return ("not", primary())
if t == "(":
x = climb(1)
if state["i"] >= len(toks) or toks[state["i"]] != ")": raise _Bad()
state["i"] += 1
return x
if len(t) == 1 and t.isalpha(): return ("atom", t)
raise _Bad()
def climb(min_level):
left = primary()
while state["i"] < len(toks):
op = toks[state["i"]]
lv = _LEVEL.get(op)
if lv is None or lv < min_level: break
state["i"] += 1
# & and | group to the left, so the right operand must bind tighter; -> and <-> group to the right
right = climb(lv if op in ("->", "<->") else lv + 1)
left = ("bin", op, left, right)
return left
tree = climb(1)
if state["i"] != len(toks): raise _Bad()
return tree
def _value(t, v):
kind = t[0]
if kind == "atom": return v[t[1]]
if kind == "not": return not _value(t[1], v)
op, x, y = t[1], _value(t[2], v), _value(t[3], v)
if op == "&": return x and y
if op == "|": return x or y
if op == "->": return y or not x
return x is y
def _atoms(trees):
found, stack = set(), list(trees)
while stack:
t = stack.pop()
if t[0] == "atom": found.add(t[1])
elif t[0] == "not": stack.append(t[1])
else: stack.append(t[2]); stack.append(t[3])
return found
def _valuation(obj, atoms):
"""The candidate must be an object with exactly the atoms that occur as keys and booleans as values."""
if not isinstance(obj, dict) or set(obj.keys()) != set(atoms): return None
for k in obj:
if obj[k] is not True and obj[k] is not False: return None
return obj
def _dig(answer, keys):
cur = answer
for k in keys:
if not isinstance(cur, dict) or k not in cur: return None
cur = cur[k]
return cur
def counterexample(answer, args):
"""answer.arguments.<id>.counterexample makes every premise true and the conclusion false."""
try:
prem = [_read(p) for p in args["premises"]]; concl = _read(args["conclusion"])
v = _valuation(_dig(answer, ["arguments", args["id"], "counterexample"]), _atoms(prem + [concl]))
if v is None: return False
return all(_value(p, v) for p in prem) and not _value(concl, v)
except Exception:
return False
def satisfying_valuation(answer, args):
"""answer.sets.<id>.valuation makes every sentence of the set true."""
try:
sents = [_read(s) for s in args["sentences"]]
v = _valuation(_dig(answer, ["sets", args["id"], "valuation"]), _atoms(sents))
if v is None: return False
return all(_value(s, v) for s in sents)
except Exception:
return False
def distinguishing_valuation(answer, args):
"""answer.pairs.<id>.distinguishing gives the two formulas different truth values."""
try:
left, right = _read(args["left"]), _read(args["right"])
v = _valuation(_dig(answer, ["pairs", args["id"], "distinguishing"]), _atoms([left, right]))
if v is None: return False
return _value(left, v) is not _value(right, v)
except Exception:
return False
def _flatten(t, op):
parts, stack = [], [t]
while stack:
x = stack.pop()
if x[0] == "bin" and x[1] == op: stack.append(x[3]); stack.append(x[2])
else: parts.append(x)
return parts
def _is_literal(t):
return t[0] == "atom" or (t[0] == "not" and t[1][0] == "atom")
def normal_form(answer, args):
"""answer.<form>.<id> is a formula in the normal form asked for (args.form is "cnf" or "dnf"), equivalent to
args.formula, built only from atoms of args.formula, and at most 2000 characters long."""
try:
form = args["form"]
if form not in ("cnf", "dnf"): return False
text = _dig(answer, [form, args["id"]])
if not isinstance(text, str) or len(text) > _MAX_LEN: return False
orig = _read(args["formula"]); cand = _read(text)
atoms = sorted(_atoms([orig]))
if not _atoms([cand]) <= set(atoms): return False
outer, inner = ("&", "|") if form == "cnf" else ("|", "&")
for part in _flatten(cand, outer):
for leaf in _flatten(part, inner):
if not _is_literal(leaf): return False
for k in range(2 ** len(atoms)):
v = dict((a, bool((k >> i) & 1)) for i, a in enumerate(atoms))
if _value(orig, v) is not _value(cand, v): return False
return True
except Exception:
return False