56 lines
2.4 KiB
Python
Executable File
56 lines
2.4 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
# randnum - random numbers in a range, with an optional seed
|
|
# Usage: randnum [MIN] [MAX] [--count N] [--float] [--unique] [--seed N]
|
|
# Defaults: MIN=0, MAX=100. Integers by default; --float gives decimals.
|
|
import argparse, random, sys
|
|
|
|
def selftest():
|
|
rng = random.Random(11)
|
|
vals = [rng.randint(1, 10) for _ in range(50)]
|
|
assert all(1 <= v <= 10 for v in vals) and len(set(vals)) > 1
|
|
assert random.Random(11).randint(1, 10) == random.Random(11).randint(1, 10)
|
|
u = random.Random(5).sample(range(1, 101), 10)
|
|
assert len(set(u)) == 10
|
|
f = random.Random(2).uniform(0, 1)
|
|
assert 0 <= f <= 1
|
|
print("randnum selftest: ok (range respected, seeded repeatability, unique, float)")
|
|
return 0
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(prog="randnum",
|
|
description="Random numbers in a range, with an optional seed.")
|
|
p.add_argument("min", nargs="?", type=float, default=0, help="minimum (default 0)")
|
|
p.add_argument("max", nargs="?", type=float, default=100, help="maximum (default 100)")
|
|
p.add_argument("--count", type=int, default=1, help="how many (default 1)")
|
|
p.add_argument("--float", action="store_true", help="emit floats instead of integers")
|
|
p.add_argument("--unique", action="store_true", help="no repeats (integers only)")
|
|
p.add_argument("--seed", type=int, help="seed for reproducible output")
|
|
p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
|
|
a = p.parse_args()
|
|
if a.selftest:
|
|
return selftest()
|
|
if a.min > a.max:
|
|
print("randnum: MIN must be <= MAX", file=sys.stderr); return 2
|
|
if a.count < 1:
|
|
print("randnum: --count must be >= 1", file=sys.stderr); return 2
|
|
rng = random.Random(a.seed) if a.seed is not None else random.SystemRandom()
|
|
if a.float:
|
|
if a.unique:
|
|
print("randnum: --unique needs integers", file=sys.stderr); return 2
|
|
for _ in range(a.count):
|
|
print(f"{rng.uniform(a.min, a.max):g}")
|
|
return 0
|
|
lo, hi = int(a.min), int(a.max)
|
|
if a.unique:
|
|
if a.count > hi - lo + 1:
|
|
print(f"randnum: only {hi - lo + 1} unique values in range", file=sys.stderr); return 2
|
|
for v in rng.sample(range(lo, hi + 1), a.count):
|
|
print(v)
|
|
else:
|
|
for _ in range(a.count):
|
|
print(rng.randint(lo, hi))
|
|
return 0
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|