gmreincglm's picture
v1 sample: 20 graded public-record tasks with answers, grader, seal
6276256 verified
Raw History Blame Contribute Delete
2.35 kB
"""Answer normalisation and comparison rules shared by the pack and grader.
integer exact match after stripping whitespace and separators
decimal1 numeric match within +/- 0.05
string case-insensitive, whitespace-collapsed
id exact after stripping surrounding whitespace
date YYYY-MM-DD, or any ISO timestamp whose date part matches
"""
from __future__ import annotations
import re
ANSWER_TYPES = ("integer", "string", "decimal1", "id", "date")
_WS = re.compile(r"\s+")
_DATE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})")
class BadAnswer(ValueError):
pass
def _text(value) -> str:
if value is None:
return ""
return str(value).strip()
def norm_integer(value):
raw = _text(value).replace(",", "").replace("_", "")
if raw.startswith("+"):
raw = raw[1:]
if re.fullmatch(r"-?\d+", raw):
return int(raw)
# tolerate an integral float such as "12.0"
try:
as_float = float(raw)
except (TypeError, ValueError):
raise BadAnswer(f"not an integer: {value!r}")
if abs(as_float - round(as_float)) > 1e-9:
raise BadAnswer(f"not an integer: {value!r}")
return int(round(as_float))
def norm_decimal1(value):
raw = _text(value).replace(",", "")
try:
return float(raw)
except (TypeError, ValueError):
raise BadAnswer(f"not a number: {value!r}")
def norm_string(value):
return _WS.sub(" ", _text(value)).casefold()
def norm_id(value):
return _text(value)
def norm_date(value):
raw = _text(value)
match = _DATE.match(raw)
if not match:
raise BadAnswer(f"not a date: {value!r}")
return f"{match.group(1)}-{match.group(2)}-{match.group(3)}"
NORMALISERS = {
"integer": norm_integer,
"decimal1": norm_decimal1,
"string": norm_string,
"id": norm_id,
"date": norm_date,
}
def equal(answer_type: str, expected, given) -> bool:
"""True when a submitted answer counts as correct for this answer type."""
if answer_type not in NORMALISERS:
raise BadAnswer(f"unknown answer_type: {answer_type!r}")
try:
want = NORMALISERS[answer_type](expected)
got = NORMALISERS[answer_type](given)
except BadAnswer:
return False
if answer_type == "decimal1":
return abs(want - got) <= 0.05
return want == got