mercredi 27 mai 2015

Python: create list of random integers where state space is limted

I would like to create a list of x random integers which are chosen from the interval [0,n[ (n is usually much bigger than x) whereby certain numbers of this interval should be ignored. I implemented that as follows:

from random import randint

def createRandomList(n, x, ignore=[]):
    myList = []
    while len(myList) < x:
        tempr = randint(0,n-1)
        if tempr not in ignore:
            myList.append(tempr)
    return myList

When I then call

l = createRandomList(5,2,ignore=[2,3])

I obtain e.g.

l = [1,4] #2 and 3 should not appear

or

l = [0,1]

or

l = [4,4]

or ...

That is the desired outcome, however, is there any faster/more compact way to do this?




Aucun commentaire:

Enregistrer un commentaire