Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python, how to generate a random integer in a range, excluding some numbers in a list?

Tags:

python

random

For example, at beginning I want generate a random integer from (0,9),

at first time, the program generate 2, then I put 2 in the 'excluding' list,

next time, I need generate a number ranging between 0 to 9, and excluding 2. let's say it the second turn, the program generate 5.

The third turn, I need generate a number ranging from 0 to 9 and excluding 2 and 5.

As the range is very huge (million level), is there any method is efficient?

like image 288
Ding Ding Avatar asked Jan 23 '26 02:01

Ding Ding


2 Answers

Generate the possible values once, shuffle that and pop values from that list each time:

values = range(10)
random.shuffle(values)

def get_value():
    return values.pop()

This will eventually produce all values in the range, in random order, without repetition.

like image 149
Martijn Pieters Avatar answered Jan 25 '26 15:01

Martijn Pieters


As per the documentation for random.sample:

To choose a sample from a range of integers, use an xrange() object as an argument. This is especially fast and space efficient for sampling from a large population: sample(xrange(10000000), 60).

This will sample without replacement, so random.sample(xrange(n), k) gives k different numbers in the range [0, n) (for k <= n).

like image 34
jonrsharpe Avatar answered Jan 25 '26 14:01

jonrsharpe