randomly generate n of each of two types

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Mon Feb 12 01:44:30 EST 2007


On Sun, 11 Feb 2007 22:20:24 -0800, Paul Rubin wrote:

> Steven D'Aprano <steve at REMOVEME.cybersource.com.au> writes:
>> If you want to avoid shuffle, here's an alternative:
>> 
>> def random_values(n, valuelist=[True, False]):
>>     N = len(valuelist)
>>     for _ in range(N*n):
>>          yield valuelist[random.randrange(0, N)]
> 
> That is not guaranteed to yield exactly equal numbers of true and false.

Neither is any random number generator. That's why because it's *random*.

Ah, I see what you mean... you're reminding me that the Original Poster
seems to want a biased set of almost-but-not-quite-randomly chosen
values, so that random_values(1) must return one each of True and False
and never True, True or False, False.

You're right, that's how the O.P. implicitly specified the problem. But it
may not be what he wants.



-- 
Steven D'Aprano 




More information about the Python-list mailing list