randomly generate n of each of two types
Alan Isaac
aisaac at american.edu
Sun Feb 11 12:18:34 EST 2007
I need access to 2*n random choices for two types
subject to a constraint that in the end I have
drawn n of each. I first tried::
def random_types(n,typelist=[True,False]):
types = typelist*n
random.shuffle(types)
for next_type in types:
yield next_type
This works but has some obvious costs.
To avoid those I considered this instead::
def random_types(n,typelist=[True,False]):
type0, type1 = typelist
ct0, ct1 = 0,0
while ct0+ct1<2*n:
if random.random() < ((n-ct0)/(2*n-ct0-ct1)):
next_type = type0
ct0 += 1
else:
next_type = type1
ct1 += 1
yield next_type
Does this seem a good way to go? Comments welcome.
Thank you,
Alan Isaac
More information about the Python-list
mailing list