Generating non-repeating random numbers in Python

This is a neat problem, and I’ve been thinking about it for a while (with solutions similar to Sjoerd’s), but in the end, here’s what I think:

Use your point 1) and stop worrying.

Assuming real randomness, the probability that a random number has already been chosen before is the count of previously chosen numbers divided by the size of your pool, i.e. the maximal number.

If you say you only need a billion numbers, i.e. nine digits: Treat yourself to 3 more digits, so you have 12-digit serial numbers (that’s three groups of four digits – nice and readable).

Even when you’re close to having chosen a billion numbers previously, the probability that your new number is already taken is still only 0,1%.

Do step 1 and draw again. You can still check for an “infinite” loop, say don’t try more than 1000 times or so, and then fallback to adding 1 (or something else).

You’ll win the lottery before that fallback ever gets used.

Leave a Comment