kenny
kenny

Reputation: 53

Randomly select 0 or 1 equal number of times?

I want to iterate over 100 values and select randomly 0 or 1, but end up with equal numbers of 0's and 1's,

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

The output is:

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 obtain the desired result?

Upvotes: 4

Views: 432

Answers (3)

NPE
NPE

Reputation: 500595

Here is a generator-based solution that uses 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))

Upvotes: 1

Phil
Phil

Reputation: 2303

Well its not truely random then but if you want to end up with 50 1s and 50 0s then use a weighting based on how many available places are left. Eg. At 40 1s and 45 0s, the chance of 0 should be 5/15, and the chance of 1 should be 10/15.

Upvotes: -1

thefourtheye
thefourtheye

Reputation: 239523

  1. Create numbers with 50 0's and 50 1's,

    >>> numbers = [0, 1] * 50
    
  2. Import shuffle from random

    >>> from random import shuffle
    
  3. shuffle them

    >>> shuffle(numbers)
    

Note: shuffle shuffles the list in-place. So, the numbers will be shuffled now.

Upvotes: 8

Related Questions