Python Forum

Full Version: Multiple Random Selections with no dulpicates
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Project Objective:
Make 5 random selections from a list of 25 items with no dultiples or numbers used more than one time.

Tried:
from random import sample
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
Chosennumber = sample(list, 5)
print("sampling with choices method ", Chosennumber)
Chosennumber = sample(list, 5)
print("sampling with choices method ", Chosennumber)
Chosennumber = sample(list, 5)
print("sampling with choices method ", Chosennumber)
Chosennumber = sample(list, 5)
print("sampling with choices method ", Chosennumber)
Chosennumber = sample(list, 5)
print("sampling with choices method ", Chosennumber)
and

 
import random
#sampling with replacement
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
#for list in list:
sampling = random.choices(list, k=5)
print("sampling with choices method ", sampling)
sampling = random.choices(list, k=5)
print("sampling with choices method ", sampling)
sampling = random.choices(list, k=5)
print("sampling with choices method ", sampling)
sampling = random.choices(list, k=5)
print("sampling with choices method ", sampling)
sampling = random.choices(list, k=5)
print("sampling with choices method ", sampling)
Those methods don't alter the original list to take out the chosen from the next selection
You could use random.shuffle
Then slice 5 off the list, then repeat 4 more times on the remaining list.
Never use list as name.

Developing Yoriz idea: one shuffle is as good as five shuffles. Therefore one can just slice shuffled list:

>>> from random import shuffle
>>> lst = list(range(1, 26))
>>> shuffle(lst)
>>> [lst[s:s+5] for s in range(0, len(lst), 5)]
[[13, 21, 8, 16, 14], [25, 4, 15, 19, 6], [20, 23, 11, 1, 9], [17, 10, 22, 5, 2], [7, 3, 12, 18, 24]]