lundi 12 janvier 2015

Python- Is there a built-in method that allows one to create an list of random numbers of size 'n' without error?

The standard way of creating a list of random numbers is:



def generateList(n):
randlist = []
for i in range(n):
randlist[i] = randint(1, 9)
return randlist


However, I recently stumbled upon random.sample, which is much more compact:



def generateList(n):
return random.sample(range(1, 10), n)


But this results in an error if n is greater than 10. So, my question is, does there exist a built-in function that does exactly what I intend it to do without running into error? If not, is there at least a more efficient alternative to the first excerpt (considering that n can be quite large)?





Aucun commentaire:

Enregistrer un commentaire