summaryrefslogtreecommitdiff
path: root/libremath/arithcheck.py
blob: d8f78ac53dcef7769647e9a6e8192e959249e9a1 (plain)
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
"""Recompute every simple binary step "a op b = c" written in a solution.
Returns the list of wrong steps (empty if all check out). Times (10:20), ratios (3:4) and
fractions written inside larger expressions are skipped rather than misread."""
import re
NUM = r"\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?"
STEP = re.compile(rf"(?<![\d.:/,])(?<!\d\s)({NUM})\s*([+\-−–×x*÷/])\s*({NUM})\s*=\s*\$?({NUM})(?![\d:/])(?!,\d)(?!\s*[+\-−–×x*÷/(^])")


def bad_steps(text):
    bad = []
    for m in STEP.finditer(text):
        a, op, b, c = m.groups()
        # skip if this is the tail of a longer expression, e.g. "2 + 3 × 4 = 14"
        pre = text[max(0, m.start() - 3):m.start()]
        if re.search(r"[+\-−–×x*÷/(]\s*$", pre): continue
        a, b, c = (float(v.replace(",", "")) for v in (a, b, c))
        if op in "×x*": v = a * b
        elif op == "+": v = a + b
        elif op in "-−–": v = a - b
        else:
            if b == 0: continue
            v = a / b
            if abs(v - c) > 1e-6 and abs(round(v, 2) - c) < 0.006: continue   # rounded quotient
            if c == int(a // b): continue                                     # whole-number quotient (remainder stated separately)
        if abs(v - c) > 1e-6 * max(1, abs(v)) and abs(round(v, 2) - c) > 1e-9:
            bad.append(m.group(0))
    return bad