File size: 1,803 Bytes
7f02d8a | 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 | """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())
|