Hafiz Muhammad Shafiq
Hafiz Muhammad Shafiq

Reputation: 8680

How to generate random numbers that are unique forever in python

I have written a script where I need a unique random number every time I run that script. Just for explaination: suppose that I want my script 5 times. Now I want number generated in all times should be unique?

I have found a lot of infomation about random number uniqueness but those are for one time only. If you think it is not possible then is there any alternative way etc.?

Upvotes: 0

Views: 471

Answers (2)

nigel222
nigel222

Reputation: 8212

Unique and random are contradictory. For anything that's genuinely random there is a (small, maybe infinitessimal) chance of repetition.

If you want something less unwieldy (but less universally unique) than UUIDs you can roll your own combination of a random number (with a small chance of repetition) and a number derived from the time (for example the Unix epoch, which won't ever repeat for a single instance if the script is run less often than once per second).

If the random number is used as part of (say) a filename you can generate a name and then check whether the file already exists. If it does, then reject the random number as already used, and generate another one. Or if you really need to, you could store all random numbers already used somewhere. Load them before each run, add the new number and save after each run.

Finally there are pseudo-"random" generators of the form X(n+1) = (X(n)*a + b) mod M. These are hopeless for security / cryptography because given a few members of the sequence, you can discover the algorithm and predict all future numbers. However, if that predictability is unimportant, then with appropriate constants you can guarantee no repeats until all M members of the sequence have been generated. The numbers are not at all random, but they may appear random to a casual observer.

Upvotes: 1

vaultah
vaultah

Reputation: 46563

You could use uuid to generate RFC 4122 UUIDs (Universally Unique IDentifiers). For example uuid4 generates a random UUID:

In [1]: import uuid

In [2]: u = uuid.uuid4()

In [3]: u
Out[3]: UUID('deb1064a-e885-4ebc-9afc-f5291120edf8')

To get the number, access the int attribute of uuid.UUID objects:

In [4]: u.int
Out[4]: 242844464987419882393579831900689854160

Upvotes: 2

Related Questions