randomly generate n of each of two types

Paul Rubin http
Sun Feb 11 12:43:53 EST 2007


"Alan Isaac" <aisaac at american.edu> writes:
> 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::

You mean you basically want to generate 2*n bools of which exactly
half are True and half are False?  Hmm (untested):

from random import random
def random_types(n):
    total = 2*n
    trues_needed = n
    for i in xrange(total):
       if random() < float(trues_needed) / float(total):
          trues_needed -= 1
          yield True
       else:
          yield False
       total -= 1



More information about the Python-list mailing list