Skip to content

Instantly share code, notes, and snippets.

@dudarev
Created October 20, 2014 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dudarev/10f94ac617aab949ecc5 to your computer and use it in GitHub Desktop.
Save dudarev/10f94ac617aab949ecc5 to your computer and use it in GitHub Desktop.
Some ways to select k random elements from a list
"""
Some solutions for @bobuk's problem discussed in
http://www.radio-t.com/p/2014/10/18/podcast-414/
"""
import random
L_TEST = [1234, 1, 23, 252, 13523, 829, 2378, 234555, 912394]
K_TEST = 3
def select1(l, k):
"""Select ``k`` random elements from list ``l``.
Suitable when len(l) is small
"""
return random.sample(l, k)
def select2(l, k):
"""Select ``k`` random elements from list ``l``.
It removes these ``k`` elements from the list.
Suitable when the list takes alsmost all memory.
"""
selection = []
len_l = len(l)
for _ in xrange(k):
i = random.randint(0, len_l - 1)
selection.append(l.pop(i))
return selection
if __name__ == '__main__':
print select1(L_TEST, K_TEST)
print select2(L_TEST, K_TEST)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment