buzhidao buzhidao - 1 month ago 6
Python Question

How to choose m random numbers from a range but with no duplicate?

For example, I need to choose three numbers from

[-2,2]
but with no duplicate, the following code can't accomplish this, I know I can do it by comparing the elements, but is there some elegant way to do so?

print(np.random.randint(-2,2,3))


Most general case is: choose
m
random numbers from range
[a,b]
with no duplicate.

Answer

Use the built-in random sample:

>>> import random
>>> random.sample(range(10), 5) # take 5 random elements from range(10)
[2, 4, 1, 7, 9]