File size: 2,345 Bytes
6276256
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"""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