1

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?

5gon12eder
  • 23,111
  • 5
  • 43
  • 89
amrcsu
  • 185
  • 1
  • 2
  • 8

3 Answers3

4

Use random.sample:

import random
random.sample(s, k)
David Zwicker
  • 22,266
  • 6
  • 57
  • 74
  • Note, if you can manage it, avoid passing `set` to `random.sample`. If I'm reading the source properly, it executes `random.sample(tuple(s), k)` -- at least for sets with length greater than 21. – mgilson Jan 08 '16 at 21:51
  • Good point. There is no need to call `set()` on the `range` object. – David Zwicker Jan 09 '16 at 01:05
1

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.

Iron Fist
  • 10,237
  • 2
  • 17
  • 32
0

Use sample from the random module.

import random
items = set(range(1, 100))
selection = set(random.sample(items, 10))
5gon12eder
  • 23,111
  • 5
  • 43
  • 89