Generate random number in range excluding some numbers
Solution 1:
Try this:
from random import choice
print choice([i for i in range(0,9) if i not in [2,5,7]])
Solution 2:
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))
Solution 3:
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