luoke-bench / mail /sampling.py
jason926's picture
Sync: scoring fixes and corrected keys from the 12-05 review
7f02d8a verified
Raw History Blame Contribute Delete
1.8 kB
"""The same N questions for every run: `--sample N --seed S` of the runners.
pick() draws by position, random.Random(seed).sample(range(len(rows)), N), and keeps the order of the set, so a set has
to stay as it is for two runs to get the same questions (the set hash in the result says whether it did).
Stdlib only.
"""
from __future__ import annotations
import random
SEED = 1203
def pick(rows, n, seed=SEED):
rows = list(rows)
if not n or n >= len(rows):
return rows
keep = set(random.Random(seed).sample(range(len(rows)), n))
return [r for i, r in enumerate(rows) if i in keep]
def pick_parts(sets, n, seed=SEED):
"""{(part, set name): rows} -> the same with N rows per part, drawn over all the sets of the part."""
if not n:
return sets
out = {}
for part in dict.fromkeys(p for p, _ in sets):
keys = [k for k in sets if k[0] == part]
keep = set(pick([(k, i) for k in keys for i in range(len(sets[k]))], n, seed))
for k in keys:
rows = [r for i, r in enumerate(sets[k]) if (k, i) in keep]
if rows:
out[k] = rows
return out
def selftest() -> int:
rows = list(range(40))
a, b = pick(rows, 10), pick(rows, 10)
sets = {("p", "x"): list(range(30)), ("p", "y"): list(range(30)), ("q", "z"): list(range(5))}
parts = pick_parts(sets, 10)
ok = (a == b and len(a) == 10 and a == sorted(a) and pick(rows, 0) == rows and pick(rows, 99) == rows
and pick(rows, 10, 7) != a and sum(len(v) for k, v in parts.items() if k[0] == "p") == 10
and parts[("q", "z")] == list(range(5)) and pick_parts(sets, 10) == parts)
print("selftest " + ("OK" if ok else "FAIL"))
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(selftest())