Datasets:
Download verify.py from udgamlabs/logic-puzzles: direct link, hf CLI and curl.
- Browser
- Download file 17.1 kB
-
https://huggingface.co/datasets/udgamlabs/logic-puzzles/resolve/main/verify.py
- Command line
-
hf download hf://datasets/udgamlabs/logic-puzzles/verify.py
-
curl -L -o verify.py https://huggingface.co/datasets/udgamlabs/logic-puzzles/resolve/main/verify.py
17.1 kB
| # Copyright 2026 Udgam Labs | |
| # SPDX-License-Identifier: Apache-2.0 | |
| """Independent check of Udgam Logic Puzzles. | |
| This program does not import the generator. It reads only the question text, parses it, solves the puzzle again with | |
| its own method (often a different algorithm from the generator's), and compares its answer with the published answer | |
| by exact string match. For families where a second solution could exist (knights and knaves, height order, zebra, | |
| cryptarithm, ages, number sequences), it also checks that the question has exactly one answer. | |
| python verify.py data/train.parquet data/test.parquet (needs pyarrow) | |
| python verify.py puzzles.jsonl | |
| """ | |
| import collections | |
| import datetime as dt | |
| import itertools | |
| import json | |
| import re | |
| import sys | |
| from fractions import Fraction | |
| WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] | |
| class Ambiguous(Exception): | |
| pass | |
| def unique(sols): | |
| sols = list(sols) | |
| if len(sols) != 1: | |
| raise Ambiguous(f"{len(sols)} solutions") | |
| return sols[0] | |
| def knights_knaves(q): | |
| stmts = [] | |
| for who, body in re.findall(r'(\w+) says: "([^"]+)"', q): | |
| if m := re.fullmatch(r"(\w+) is a knight\.", body): | |
| stmts.append((who, m[1], "is")) | |
| elif m := re.fullmatch(r"(\w+) and I are the same kind\.", body): | |
| stmts.append((who, m[1], "same")) | |
| elif m := re.fullmatch(r"(\w+) and I are different kinds\.", body): | |
| stmts.append((who, m[1], "diff")) | |
| else: | |
| raise ValueError(body) | |
| people = sorted({p for s in stmts for p in s[:2]}) | |
| def ok(knight): | |
| for who, other, kind in stmts: | |
| claim = {"is": knight[other], "same": knight[who] == knight[other], "diff": knight[who] != knight[other]}[kind] | |
| if claim != knight[who]: # a knight's claim is true, a knave's is false | |
| return False | |
| return True | |
| sol = unique(k for k in (dict(zip(people, v)) for v in itertools.product([False, True], repeat=len(people))) if ok(k)) | |
| return ", ".join(p for p in people if sol[p]) or "none" | |
| def height_order(q): | |
| clues = re.findall(r"(\w+) is taller than (\w+)\.", q) | |
| people = sorted({p for c in clues for p in c}) | |
| sol = unique(p for p in itertools.permutations(people) | |
| if all(p.index(a) < p.index(b) for a, b in clues)) | |
| return ", ".join(sol) | |
| def grid_paths(q): | |
| r, c = map(int, re.search(r"(\d+)-row by (\d+)-column", q).groups()) | |
| blocked = {(int(a) - 1, int(b) - 1) for a, b in re.findall(r"\(row (\d+), column (\d+)\)", q)} | |
| total = 0 | |
| for downs in itertools.combinations(range(r + c - 2), r - 1): # enumerate every right/down path | |
| i = j = 0 | |
| okay = (0, 0) not in blocked | |
| for step in range(r + c - 2): | |
| if step in downs: | |
| i += 1 | |
| else: | |
| j += 1 | |
| okay = okay and (i, j) not in blocked | |
| total += okay | |
| return str(total) | |
| def variable_chain(q): | |
| body = re.search(r"Each line defines a variable\. (.*)\. What is the value of (\w)\?", q) | |
| defs = dict(line.split("=") for line in body[1].split("; ")) | |
| memo = {} | |
| def value(v): | |
| if v not in memo: | |
| m = re.fullmatch(r"(\w)([+-])(\w)", defs[v]) | |
| if not m: | |
| memo[v] = int(defs[v]) | |
| else: | |
| x = value(m[1]) | |
| y = int(m[3]) if m[3].isdigit() else value(m[3]) | |
| memo[v] = x + y if m[2] == "+" else x - y | |
| return memo[v] | |
| return str(value(body[2])) | |
| def _parse_date(s): | |
| return dt.datetime.strptime(s, "%B %d, %Y").date() | |
| def calendar(q): | |
| if m := re.match(r"(\w+ \d+, \d+) is a (\w+)\. .* what day of the week is (\w+ \d+, \d+)\?", q): | |
| a, wd, b = _parse_date(m[1]), m[2], _parse_date(m[3]) | |
| if WEEKDAYS[a.weekday()] != wd: | |
| raise ValueError("stated weekday is wrong") | |
| return WEEKDAYS[(WEEKDAYS.index(wd) + (b - a).days) % 7] # count on from the stated weekday | |
| m = re.match(r"How many days are there from (\w+ \d+, \d+) to (\w+ \d+, \d+), (counting both|not counting)", q) | |
| a, b = _parse_date(m[1]), _parse_date(m[2]) | |
| return str(b.toordinal() - a.toordinal() + (m[3] == "counting both")) | |
| def water_jugs(q): | |
| a, b, t = map(int, re.search(r"empty (\d+)-litre jug and an empty (\d+)-litre jug.*exactly (\d+) litres", q).groups()) | |
| frontier, seen, steps = {(0, 0)}, {(0, 0)}, 0 | |
| while frontier: | |
| if any(t in s for s in frontier): | |
| return str(steps) | |
| nxt = set() | |
| for x, y in frontier: | |
| pour_xy, pour_yx = min(x, b - y), min(y, a - x) | |
| for s in ((a, y), (x, b), (0, y), (x, 0), (x - pour_xy, y + pour_xy), (x + pour_yx, y - pour_yx)): | |
| if s not in seen: | |
| seen.add(s) | |
| nxt.add(s) | |
| frontier, steps = nxt, steps + 1 | |
| raise ValueError("unreachable") | |
| def cryptarithm(q): | |
| wx, wy, ws = re.search(r"In the addition (\w+) \+ (\w+) = (\w+),", q).groups() | |
| letters = sorted(set(wx + wy + ws)) | |
| def num(w, m): | |
| n = 0 | |
| for ch in w: | |
| n = n * 10 + m[ch] | |
| return n | |
| sols = [] | |
| for digits in itertools.permutations(range(10), len(letters)): | |
| m = dict(zip(letters, digits)) | |
| if 0 in (m[wx[0]], m[wy[0]], m[ws[0]]): | |
| continue | |
| if num(wx, m) + num(wy, m) == num(ws, m): | |
| sols.append(num(ws, m)) | |
| return str(unique(sols)) | |
| def shortest_route(q): | |
| roads = re.findall(r"(\w+)-(\w+): (\d+) km", q) | |
| src, dst = re.search(r"shortest route from (\w+) to (\w+)\?", q).groups() | |
| towns = sorted({t for r in roads for t in r[:2]}) | |
| inf = float("inf") | |
| d = {(u, v): 0 if u == v else inf for u in towns for v in towns} | |
| for u, v, w in roads: | |
| d[u, v] = d[v, u] = min(d[u, v], int(w)) | |
| for k in towns: # Floyd-Warshall (the generator uses Dijkstra) | |
| for i in towns: | |
| for j in towns: | |
| if d[i, k] + d[k, j] < d[i, j]: | |
| d[i, j] = d[i, k] + d[k, j] | |
| return str(d[src, dst]) | |
| def venn(q): | |
| total = int(re.match(r"In a group of (\d+) students, ", q)[1]) | |
| body = q[q.index("students, ") + len("students, "):] | |
| body = re.split(r"\. How many|, and \d+ like none of them\.", body)[0] | |
| single, pair, triple = {}, {}, None | |
| for fact in body.split(", "): | |
| if m := re.fullmatch(r"(\d+) like all three", fact): | |
| triple = int(m[1]) | |
| elif m := re.fullmatch(r"(\d+) like both (.+) and (.+)", fact): | |
| pair[frozenset((m[2], m[3]))] = int(m[1]) | |
| elif m := re.fullmatch(r"(\d+) like (.+)", fact): | |
| single[m[2]] = int(m[1]) | |
| else: | |
| raise ValueError(fact) | |
| things = list(single) | |
| union = sum(single.values()) - sum(pair.values()) + (triple or 0) # inclusion-exclusion | |
| if "like none of these" in q: | |
| return str(total - union) | |
| target = re.search(r"How many like (.+) but none of the others\?", q)[1] | |
| only = single[target] - sum(v for k, v in pair.items() if target in k) + (triple or 0) | |
| neither = int(re.search(r", and (\d+) like none of them\.", q)[1]) | |
| if total - union != neither: | |
| raise ValueError("counts do not add up") | |
| assert len(things) in (2, 3) | |
| return str(only) | |
| def number_sequence(q): | |
| s = [int(x) for x in re.search(r"sequence\? (.*), \.\.\.", q)[1].split(", ")] | |
| preds = set() | |
| d = [b - a for a, b in zip(s, s[1:])] | |
| if len(set(d)) == 1: # arithmetic | |
| preds.add(s[-1] + d[0]) | |
| if len(set(b - a for a, b in zip(d, d[1:]))) == 1: # constant second difference (quadratic) | |
| preds.add(s[-1] + d[-1] + (d[-1] - d[-2])) | |
| if all(s[i] == s[i - 1] + s[i - 2] for i in range(2, len(s))): # each term is the sum of the two before | |
| preds.add(s[-1] + s[-2]) | |
| if s[1] != s[0]: # x -> m*x + c (geometric when c = 0) | |
| m = Fraction(s[2] - s[1], s[1] - s[0]) | |
| c = s[1] - m * s[0] | |
| if all(s[i] == m * s[i - 1] + c for i in range(1, len(s))): | |
| preds.add(m * s[-1] + c) | |
| ev, od = s[0::2], s[1::2] # two interleaved arithmetic sequences | |
| if len(set(b - a for a, b in zip(ev, ev[1:]))) == 1 and len(set(b - a for a, b in zip(od, od[1:]))) == 1: | |
| nxt = ev if len(s) % 2 == 0 else od # the part the next term belongs to | |
| preds.add(nxt[-1] + (nxt[1] - nxt[0])) | |
| if len(preds) != 1: | |
| raise Ambiguous(f"rules predict {sorted(preds)}") | |
| p = preds.pop() | |
| return str(int(p)) | |
| def clock_angle(q): | |
| h, m = map(int, re.search(r"clock at (\d+):(\d+)\?", q).groups()) | |
| minute_hand, hour_hand = 6 * m, (h % 12) * 30 + Fraction(m, 2) | |
| diff = abs(minute_hand - hour_hand) % 360 | |
| a = min(diff, 360 - diff) | |
| return str(int(a)) if a.denominator == 1 else f"{float(a):g}" | |
| def task_schedule(q): | |
| body = re.search(r"A project has these tasks: (.*)\. Any number of tasks", q)[1] | |
| dur, pre = {}, {} | |
| for part in body.split("; "): | |
| m = re.fullmatch(r"task (\w) takes (\d+) (?:hours|days)(?: and can start only after (.+) (?:is|are) finished)?", part) | |
| dur[m[1]] = int(m[2]) | |
| pre[m[1]] = m[3].split(" and ") if m[3] else [] | |
| memo = {} | |
| def finish(t): | |
| if t not in memo: | |
| memo[t] = dur[t] + max((finish(p) for p in pre[t]), default=0) | |
| return memo[t] | |
| return str(max(finish(t) for t in dur)) | |
| def ages(q): | |
| x, y, s = re.match(r"(\w+) and (\w+) have ages that add up to (\d+) years\.", q).groups() | |
| s = int(s) | |
| if m := re.search(r"In (\d+) years, \w+ will be (\d+) times as old", q): | |
| k, r = int(m[1]), int(m[2]) | |
| b = Fraction(s + k - r * k, r + 1) # (s - b) + k = r (b + k) | |
| else: | |
| m = re.search(r"(\d+) years ago, \w+ was (\d+) times as old", q) | |
| k, r = int(m[1]), int(m[2]) | |
| b = Fraction(s - k + r * k, r + 1) # (s - b) - k = r (b - k) | |
| if b - k < 1: | |
| raise Ambiguous("no valid age") | |
| if b.denominator != 1: | |
| raise Ambiguous("no whole-number solution") | |
| return str(s - int(b)) | |
| def digit_count(q): | |
| m = re.search(r"Using only the digits ([\d, ]+) \((digits may repeat|each digit at most once)\), how many (\d)-digit " | |
| r"numbers can be made that are (.+)\? A number", q) | |
| pool, rep, L, cond = set(m[1].split(", ")), m[2] == "digits may repeat", int(m[3]), m[4] | |
| if cond == "even": | |
| test = lambda n: n % 2 == 0 # noqa: E731 | |
| elif cond == "odd": | |
| test = lambda n: n % 2 == 1 # noqa: E731 | |
| elif cond.startswith("divisible by "): | |
| k = int(cond.split()[-1]) | |
| test = lambda n: n % k == 0 # noqa: E731 | |
| else: | |
| thr = int(re.fullmatch(r"greater than (\d+)", cond)[1]) | |
| test = lambda n: n > thr # noqa: E731 | |
| count = 0 | |
| for n in range(10 ** (L - 1), 10 ** L): # every L-digit number, checked one by one | |
| ds = str(n) | |
| if set(ds) <= pool and (rep or len(set(ds)) == L) and test(n): | |
| count += 1 | |
| return str(count) | |
| def knight_moves(q): | |
| n = int(re.search(r"On a (\d+)x\d+ chessboard", q)[1]) | |
| start = re.search(r"a knight stands on (\w\d)\.", q)[1] | |
| target = re.search(r"needs to reach (\w\d)\?", q)[1] | |
| bl = re.search(r"may not land on these squares: ([^.]+)\.", q) | |
| blocked = set(bl[1].split(", ")) if bl else set() | |
| sq = lambda f, r: "abcdefgh"[f] + str(r + 1) # noqa: E731 | |
| pos = {start} | |
| for moves in range(1, n * n + 1): | |
| pos = pos | {sq(f + df, r + dr) for p in pos for f, r in [("abcdefgh".index(p[0]), int(p[1:]) - 1)] | |
| for df, dr in itertools.permutations([1, 2, -1, -2], 2) if abs(df) != abs(dr) | |
| if 0 <= f + df < n and 0 <= r + dr < n and sq(f + df, r + dr) not in blocked} | |
| if target in pos: | |
| return str(moves) | |
| raise ValueError("unreachable") | |
| def zebra(q): | |
| m = re.match(r"(\d) people \(([^)]+)\) live in \d houses in a row", q) | |
| n, people = int(m[1]), m[2].split(", ") | |
| props = {} | |
| for cat, vals in re.findall(r"the (pet|drink|colour)s are ([a-z, ]+?)(?:;|\. Clues)", q): | |
| props[cat] = vals.split(", ") | |
| clues_txt = re.search(r"Clues: (.*)\. Who ", q)[1].split(". ") | |
| ask = re.search(r"\. Who (owns the (\w+)|drinks (\w+)|lives in the (\w+) house)\? Answer", q) | |
| def thing(t): | |
| t = t[0].lower() + t[1:] if t.startswith("The ") else t | |
| if t in people: | |
| return ("name", t) | |
| if m := re.fullmatch(r"the (\w+) owner", t): | |
| return ("pet", m[1]) | |
| if m := re.fullmatch(r"the person who drinks (\w+)", t): | |
| return ("drink", m[1]) | |
| if m := re.fullmatch(r"the person in the (\w+) house", t): | |
| return ("colour", m[1]) | |
| raise ValueError(t) | |
| clues = [] | |
| for c in clues_txt: | |
| if m := re.fullmatch(r"(.+) lives in house (\d)", c): | |
| clues.append(("pos", thing(m[1]), int(m[2]) - 1)) | |
| elif m := re.fullmatch(r"(.+) lives directly to the left of (.+)", c): | |
| clues.append(("left", thing(m[1]), thing(m[2]))) | |
| elif m := re.fullmatch(r"(.+) lives next to (.+)", c): | |
| clues.append(("next", thing(m[1]), thing(m[2]))) | |
| elif m := re.fullmatch(r"(.+) is not (.+)", c): | |
| clues.append(("not", thing(m[1]), thing(m[2]))) | |
| elif m := re.fullmatch(r"(.+) is (.+)", c): | |
| clues.append(("same", thing(m[1]), thing(m[2]))) | |
| else: | |
| raise ValueError(c) | |
| cats = ["name"] + list(props) | |
| values = {"name": people, **props} | |
| def house(sol, t): | |
| return sol[t[0]].index(t[1]) | |
| sols = [] | |
| for combo in itertools.product(*[itertools.permutations(values[c]) for c in cats]): | |
| sol = dict(zip(cats, combo)) | |
| okay = True | |
| for c in clues: | |
| if c[0] == "pos": | |
| okay = house(sol, c[1]) == c[2] | |
| elif c[0] == "left": | |
| okay = house(sol, c[1]) + 1 == house(sol, c[2]) | |
| elif c[0] == "next": | |
| okay = abs(house(sol, c[1]) - house(sol, c[2])) == 1 | |
| elif c[0] == "not": | |
| okay = house(sol, c[1]) != house(sol, c[2]) | |
| else: | |
| okay = house(sol, c[1]) == house(sol, c[2]) | |
| if not okay: | |
| break | |
| if okay: | |
| sols.append(sol) | |
| sol = unique(sols) | |
| cat, val = (("pet", ask[2]) if ask[2] else ("drink", ask[3]) if ask[3] else ("colour", ask[4])) | |
| return sol["name"][sol[cat].index(val)] | |
| def balance_scale(q): | |
| m = re.search(r"On a balance scale, (\d+) (\w+) weighs? the same as (\d+) (\w+), and (\d+) (\w+) weighs? the same " | |
| r"as (\d+) (\w+)\. .* How many (\w+) weigh the same as (\d+) (\w+)\?", q) | |
| one = lambda w: w[:-2] if w.endswith("oes") else w[:-1] if w.endswith("s") else w # noqa: E731 | |
| a1, f0, b1, f1, a2, f1b, b2, f2, ask, k, f0b = m.groups() | |
| if not (one(f1) == one(f1b) and one(f0) == one(f0b) and one(ask) == one(f2)): | |
| raise ValueError("fruits do not chain") | |
| w0 = Fraction(1) | |
| w1 = int(a1) * w0 / int(b1) | |
| w2 = int(a2) * w1 / int(b2) | |
| ans = int(k) * w0 / w2 | |
| if ans.denominator != 1: | |
| raise Ambiguous("not a whole number") | |
| return str(int(ans)) | |
| SOLVERS = {f.__name__: f for f in [ | |
| knights_knaves, height_order, grid_paths, variable_chain, calendar, water_jugs, cryptarithm, shortest_route, venn, | |
| number_sequence, clock_angle, task_schedule, ages, digit_count, knight_moves, zebra, balance_scale]} | |
| def load(path): | |
| if path.endswith(".parquet"): | |
| import pyarrow.parquet as pq | |
| return pq.read_table(path).to_pylist() | |
| return [json.loads(line) for line in open(path)] | |
| def main(paths): | |
| stats = collections.defaultdict(collections.Counter) | |
| problems = [] | |
| for path in paths: | |
| for row in load(path): | |
| fam = row["family"] | |
| try: | |
| got = SOLVERS[fam](row["question"]) | |
| stats[fam]["agree" if got == row["answer"] else "disagree"] += 1 | |
| if got != row["answer"]: | |
| problems.append((row["id"], "disagree", got, row["answer"])) | |
| except Ambiguous as e: | |
| stats[fam]["ambiguous"] += 1 | |
| problems.append((row["id"], "ambiguous", str(e), row["answer"])) | |
| except Exception as e: # noqa: BLE001 | |
| stats[fam]["parse_error"] += 1 | |
| problems.append((row["id"], "error", repr(e), row["answer"])) | |
| total = collections.Counter() | |
| for fam in SOLVERS: | |
| total.update(stats[fam]) | |
| print(f"{fam:16s} " + " ".join(f"{k} {v}" for k, v in sorted(stats[fam].items()))) | |
| print("TOTAL", dict(total)) | |
| for p in problems[:20]: | |
| print(" ", p) | |
| return total, stats, problems | |
| if __name__ == "__main__": | |
| t, _, _ = main(sys.argv[1:]) | |
| sys.exit(0 if set(t) == {"agree"} else 1) | |