简体   繁体   English

随机选择0或1次相等的次数?

[英]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, 我想迭代超过100个值并随机选择0或1,但最终得到相同数字的0和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

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? 如何更改代码以获得所需的结果?

  1. Create numbers with 50 0's and 50 1's, 创建numbers与50 0和50 1的,

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

     >>> from random import shuffle 
  3. shuffle them shuffle他们

     >>> shuffle(numbers) 

Note: shuffle shuffles the list in-place. 注意: shuffle将列表shuffle So, the numbers will be shuffled now. 所以,这些numbers现在将被洗牌。

Here is a generator-based solution that uses O(1) memory: 这是一个使用O(1)内存的基于生成器的解决方案:

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))

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. 那么它并不是真正随机的,但是如果你想最终得到50个1和50个0,那么根据剩余的可用位数使用加权。 Eg. 例如。 At 40 1s and 45 0s, the chance of 0 should be 5/15, and the chance of 1 should be 10/15. 在40 1s和45 0s,0的概率应该是5/15,1的几率应该是10/15。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 是否有 function 我可以在 Python 中随机使用 select 等于指定数量的元素并将其更改为另一个? - Is there a function I can use in Python to randomly select elements equal to specified number and change it to another? 随机选择一个数字,然后随机选择一个更大的数字python代码? - Select a number randomly and then select a higher number randomly python code? 重复列表中元素的次数相等 - Repeating elements in list equal number of times 从列表中随机选择 x 个元素 - Randomly select x number of elements from a list 将字符串追加到列表的次数等于单独列表中的数字 - Appending string to list number of times equal to number in separate list 使用python实现相同次数的字符串匹配函数 - Implementing a function using python for string matching with equal number of times 使用重复相同次数的范围内的数字填充 Pyspark Dataframe 列 - Populate Pyspark Dataframe Column with numbers in a range repeated equal number of times 计算dataframe两列同时等于-1的次数 - To calculate the number of times the two dataframe columns are equal to -1 at the same time 将 Grid position 增加一个数字,随机拆分等于该数字的 x 和 y - Increase Grid position by a number, randomly split over x & y that equal that number Python,多次打印内容 - Python, printing things a select number of times
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM