Generating non-repeating random numbers in Python

前端 未结 17 1764
粉色の甜心
粉色の甜心 2020-11-30 19:56

Ok this is one of those trickier than it sounds questions so I\'m turning to stack overflow because I can\'t think of a good answer. Here is what I want: I need Python to ge

17条回答
  •  悲&欢浪女
    2020-11-30 20:51

    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.

提交回复
热议问题