Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random number in range excluding some numbers

Tags:

python

random

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?

like image 903
Kewl Avatar asked Mar 24 '17 12:03

Kewl


People also ask

How do I randomize a number within a range in Excel?

Select the cells in which you want to get the random numbers. In the active cell, enter =RAND() Hold the Control key and Press Enter. Select all the cell (where you have the result of the RAND function) and convert it to values.

How do I restrict random numbers in Java?

You can restrict the random numbers between a certain range by providing the minimum and maximum values as arguments. In addition to Random. ints() , Java 8 also introduced Random. doubles() and Random.


1 Answers

Try this:

from random import choice

print choice([i for i in range(0,9) if i not in [2,5,7]])
like image 98
McGrady Avatar answered Oct 09 '22 03:10

McGrady