In your question, the question arises about a 4-byte random hex generator, but in the comments you clarify that you only need four hexadecimal digits, which means that there are only 2**16 combinations. This complicates the task: we simply create a list of 65,536 combinations and shuffle it, and then we can simply iterate over this shuffled list. To save a little time and RAM, I create a list of integers and simply convert the integers to hexadecimal strings as needed.
The fact that you have a list of 124 codes that are already in use adds a bit of complexity, but we can handle this by putting these codes in a set; we can easily test the generated codes to see if they are in the used set.
Obviously, we want to be able to run the program several times, so we save the index number of the shuffled list in a text file. This is simpler and more efficient than storing every number that we generate in the used set.
We also need randomization to be consistent, so we need to provide the seed to the random number generator.
Here is the Python 3 code. It can be adapted to work in Python 2 (by changing FileNotFoundError to IOError ), but you cannot switch versions between runs because the sequence of random numbers generated by Python 2 will not be the same as the one created by Python 3
from random import seed, shuffle passphrase = 'My secret passphrase' seed(passphrase)
output from 3 runs
Using index 0 Code: d0fc Saving index 1 Using index 1 Code: d7e9 Saving index 3 Using index 3 Code: fc42 Saving index 4
As you can see, index 2 is skipped because it matches the code in the used set.
PM 2Ring
source share