jeudi 11 novembre 2021

ValueError: Sample larger than population or is negative (with n=5)

I have wrote a code to get a group of persons randomly. The aim is that when one person is already choose randomly, the program should remove him. I have use random.sample() function and it work well for n=1,2,3,4 when I reach 5, it give me an error and till now I am trying to understand what is happen behind this function. Any explanation and hint will be helful. Thanks!

import random
ma_list =["anne","aline","gros","eve","armand","yves","elv","allo","sonia","luc","marc","jules","kevin"]
#this will contain an occurence of our list
maListOc = ma_list
#this list will contain our random list
random_list = None
groupe = 1
#for each element in ma_list, we randome and put into our variable
for i in ma_list:
    random_list = random.sample(ma_list, 5)
    #then we remove data already randomize in our list, but the complexity is high for this little program
    for element in random_list:
        ma_list.remove(element)
    print("Goupe N°:",groupe)
    #and we finally print our randomized list 
    print(random_list)
    print("______________________________")
    groupe += 1
print(maListOc)

here is the Output:

Goupe N°: 1
['aline', 'gros', 'armand', 'sonia', 'anne']
______________________________
Goupe N°: 2
['kevin', 'allo', 'eve', 'elv', 'marc']
______________________________
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-29-c2d13d61c8d1> in <module>
      8 #for each element in ma_list, we randome and put into our variable
      9 for i in ma_list:
---> 10     random_list = random.sample(ma_list, 5)
     11     #then we remove data already randomize in our list, but the complexity is high for this little program
     12     for element in random_list:

~\anaconda3\lib\random.py in sample(self, population, k)
    361         n = len(population)
    362         if not 0 <= k <= n:
--> 363             raise ValueError("Sample larger than population or is negative")
    364         result = [None] * k
    365         setsize = 21        # size of a small set minus size of an empty list

ValueError: Sample larger than population or is negative



Aucun commentaire:

Enregistrer un commentaire