Is there a simple way in Python to generate a random number in a range excluding some subset of numbers in that range?
For example, I know that you can generate a random number between 0 and 9 with:
from random import randint
randint(0,9)
What if I have a list, e.g. exclude=[2,5,7], that I don't want to be returned?
Try this:
from random import choice
print choice([i for i in range(0,9) if i not in [2,5,7]])
Try with something like this:
from random import randint
def random_exclude(*exclude):
exclude = set(exclude)
randInt = randint(0,9)
return my_custom_random() if randInt in exclude else randInt
print(random_exclude(2, 5, 7))
If you have larger lists, i would recommend to use set operations because they are noticeable faster than the recomended answer.
random.choice(list(set([x for x in range(0, 9)]) - set(to_exclude)))
I took took a few tests with both the accepted answer and my code above.
For each test i did 50 iterations and measured the average time. For testing i used a range of 999999.
to_exclude size 10 elements:
Accepted answer = 0.1782s
This answer = 0.0953s
to_exclude size 100 elements:
Accepted answer = 01.2353s
This answer = 00.1117s
to_exclude size 1000 elements:
Accepted answer = 10.4576s
This answer = 00.1009s