Dup Ver Goto 📝

Python Struct Pack Unpack

To
22 lines, 102 words, 762 chars Page 'PackUnpack' does not exist.

See the docs.

Examples

Pseudorandomly and deterministically choose from a list of arguments. The first argument idx is hashed, turned into an integer, reduced modulo the length of the list of remaining arguments, and that argument returned. That is, given the same idx, and the same list of arguments, it will return the same argument every time (unlike using random.choice).

import sys, hashlib, struct
args = sys.argv[1:]
if len(args) < 2:
  print(f"choosed idx args...",file=sys.stderr)
  print(f"  idx is hashed and reduced mod to choose")
  exit(1)
idx, *args = args
sha = hashlib.sha256()
sha.update(idx.encode())
h = sha.digest()
i, = struct.unpack(">Q",h[:8])
print(args[i%len(args)])