buzhidao buzhidao - 1 year ago 71
Python Question

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

For example, I need to choose three numbers from

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?


Most general case is: choose
random numbers from range
with no duplicate.

Answer Source

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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download