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
  • 24,280
  • 5
  • 45
  • 92
amrcsu
  • 185
  • 1
  • 2
  • 8

3 Answers3

4

Use random.sample:

import random
random.sample(s, k)
David Zwicker
  • 23,581
  • 6
  • 62
  • 77
  • 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
  • `X = {1,2,3,4}; random.sample(X, 1)` DeprecationWarning: Sampling from a set deprecated since Python 3.9 and will be removed in a subsequent version. – Ross Bencina Aug 15 '23 at 21:21
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,739
  • 2
  • 18
  • 34
0

Use sample from the random module.

import random
items = set(range(1, 100))
selection = set(random.sample(items, 10))
5gon12eder
  • 24,280
  • 5
  • 45
  • 92