Random number help

Larry Hudson orgnut at yahoo.com
Thu Nov 24 01:02:30 EST 2016


On 11/23/2016 11:17 AM, Thomas Grops 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
>
> Many Thanks Tom
>

Here's a possible generic approach:

#  Come up with a better name for this function
def randx(lo, hi, nw):  #  nw is a list of not-wanted ints
     while True:
         n = random.randint(lo, hi)
         if n not in nw:
             return n

Use it the same way as randint(), plus a list of the not-wanted values.
Short example:

-------
nw = [1, 3, 5, 7, 9]  #  Odd numbers out
for i in range(10):
     print(randx(1, 10, nw), end=' ')
print()
-------

Here's the results I got for 3 runs...

4 4 4 8 10 6 8 2 4 8
8 4 2 4 6 8 2 4 8 8
10 6 6 4 4 4 8 2 8 4

Of course, the not-wanted list can be a single int, or even empty.

-- 
      -=- Larry -=-



More information about the Python-list mailing list