Download graders/ea_ring_loading_15/check.py from amphora/MathConstructOptimize-Envs: direct link, hf CLI and curl.
- Browser
- Download file 1.97 kB
-
https://huggingface.co/datasets/amphora/MathConstructOptimize-Envs/resolve/main/graders/ea_ring_loading_15/check.py
- Command line
-
hf download hf://datasets/amphora/MathConstructOptimize-Envs/graders/ea_ring_loading_15/check.py
-
curl -L -o check.py https://huggingface.co/datasets/amphora/MathConstructOptimize-Envs/resolve/main/graders/ea_ring_loading_15/check.py
1.97 kB
| """Ring loading problem with 15 pairs (EinsteinArena ring-loading-15, MIT). | |
| A(u, v) = min over z_i in {v_i, -u_i} of max_k |sum_{i<=k} z_i - sum_{i>k} z_i| (maximize). | |
| Audit: upstream verifier parses exact rationals and enumerates all 2^15 adversary choices; sound. | |
| Re-implemented over a common denominator with Python integers (same exact value, faster).""" | |
| import math | |
| import re | |
| from fractions import Fraction | |
| from run import Invalid | |
| PAT = re.compile(r"^(?:0|[1-9]\d*)(?:(?:\.\d+)|(?:/[1-9]\d*))?$") | |
| def _rat(s): | |
| if not isinstance(s, str) or not 1 <= len(s) <= 80 or PAT.fullmatch(s) is None: | |
| raise Invalid("values must be nonnegative decimal or fraction strings such as '0.25' or '3/7'") | |
| r = Fraction(s) | |
| if r.numerator.bit_length() > 64 or r.denominator.bit_length() > 64: | |
| raise Invalid("reduced numerator and denominator must fit in 64 bits") | |
| return r | |
| def check(inst, ans): | |
| k = inst["pairs"] | |
| p = ans.get("pairs") | |
| if not isinstance(p, list) or len(p) != k: | |
| raise Invalid(f"pairs must be a list of exactly {k} pairs") | |
| uv = [] | |
| for q in p: | |
| if not isinstance(q, list) or len(q) != 2: | |
| raise Invalid("each entry must be a pair [u, v]") | |
| u, v = _rat(q[0]), _rat(q[1]) | |
| if u + v > 1: | |
| raise Invalid("every pair must satisfy u + v <= 1") | |
| uv.append((u, v)) | |
| den = 1 | |
| for u, v in uv: | |
| for r in (u, v): | |
| den = den * r.denominator // math.gcd(den, r.denominator) | |
| U = [int(u * den) for u, _ in uv] | |
| V = [int(v * den) for _, v in uv] | |
| best = None | |
| for mask in range(1 << k): | |
| z = [-U[i] if mask >> i & 1 else V[i] for i in range(k)] | |
| tot = sum(z) | |
| pre, worst = 0, 0 | |
| for x in z: | |
| pre += x | |
| worst = max(worst, abs(2 * pre - tot)) | |
| if best is None or worst < best: | |
| best = worst | |
| return float(Fraction(best, den)), {"exact": str(Fraction(best, den))} | |