Random number help

Chris Kaynor ckaynor at zindagigames.com
Wed Nov 23 14:29:43 EST 2016


On Wed, Nov 23, 2016 at 11:17 AM, Thomas Grops via Python-list
<python-list at python.org> wrote:
> I need a way of generating a random number but there is a catch:
>
> I don't want to include certain numbers, is this possible?
>
> random.randint(1,100) works as it will randomly pick numbers between 1 and 100 but say i don't want 48 to come out is there a way of doing this. It needs to be an integer too so not a list unless there is a way to convert list to int

There are a few ways to accomplish this, depending on the exact
requirements. Here are some basic ideas:
- Generate a list of all valid values, and take the one at a random
index. random.sample may be useful. This is guaranteed to complete
(and in only one try), but generally takes extra memory. It is also a
reasonably easy way to sample without replacement (remove the picked
item each time).
- Generate a random number from the larger range, and retry if you get
one in the invalid set. Basically akin to rolling a die, and rerolling
until you don't get a 6. This could theoretically take forever,
however it is often good enough in practice. This will become more and
more inefficient as set of invalid values grows (especially if the
invalid set is a superset of the whole range)



More information about the Python-list mailing list