Randomly select 0 or 1 an equal number of times?

I want to iterate over more than 100 values ​​and choose randomly 0 or 1, but in the end we get equal numbers 0 and 1,

The code below prints the counts:

import random
c_true = 0
c_false = 0

for i in range(100):
    a = random.getrandbits(1)
    if a == 1:
        c_true += 1
    else:
        c_false += 1

print "true_count:",c_true
print "false_count:",c_false

      

Output:

true_count: 56
false_count: 44

      

I want the counts to be equal

true_count: 50
false_count: 50

      

How can I change the code to get the desired result?

+3


source to share


3 answers




Note. shuffle

shuffles the list in place. So, it numbers

will be shuffled.

+9


source


Here is a generator based solution using O (1) memory:



import random

def gen_boolean_seq(true_count, false_count):
   while true_count or false_count:
      val = (random.random() >= false_count / float(true_count + false_count))
      if val:
         true_count -= 1
      else:
         false_count -= 1
      yield val

print sum(gen_boolean_seq(50, 50))

      

+3


source


Well, that's not true, but if you want to end up with 50 1 and 50 0 then use weighting based on the number of seats available. For example. At 40 1s and 45 0, the odds of 0 should be 5/15, and the odds of 1 should be 10/15.

0


source







All Articles