Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a random number that is not in a blacklist of integers?

Tags:

python

I'd like to be able to get random integers except for numbers in my blacklist array, I'm having some trouble understanding how I can iterate the code again till it finds the good number.

Python

def viewName(...):
    random_int = random.randint(0, 11)
    blacklist = [1, 2, 3, 5, 6, 10]

    for bl in blacklist:
        if random_int == bl:
            #try again till there's a number that isn't in the blacklist
        else:
            correctNumber = random_int
...

This seems pretty basic but I don't understand how I can iterate over and over till there's a good number, what is the fastest and more efficient way to achieve this, any suggestion?

like image 738
Hiroyuki Nuri Avatar asked Oct 19 '25 03:10

Hiroyuki Nuri


1 Answers

Rather than re-sampling, just sample from pre-prepared data with the blacklisted items already removed:

import random

choices = list(set(range(12)).difference(blacklist))
n = random.choice(choices)
like image 164
wim Avatar answered Oct 22 '25 03:10

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!