If I have a set like so:
s = set(range(1,100))
How might I randomly generate a subset of s
containing k
distinct elements?
If I have a set like so:
s = set(range(1,100))
How might I randomly generate a subset of s
containing k
distinct elements?
Use random.sample
:
import random
random.sample(s, k)
Use random
module:
>>> random.sample(s, 10)
[14, 43, 42, 18, 80, 63, 15, 59, 49, 57]
There is no need for you to s=set(range(100))
as range
will provide a list of numbers in ascending order from 0 to 99.So, all of them are unique.
Just feed that range(1,100)
to the random.sample
method:
>>> random.sample(range(1,100), k)
Quoting from Python Docs:
random.sample(population, k)
Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.
Use sample
from the random
module.
import random
items = set(range(1, 100))
selection = set(random.sample(items, 10))