[英]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? 如何更改代码以获得所需的结果?
Create numbers
with 50 0's and 50 1's, 创建
numbers
与50 0和50 1的,
>>> numbers = [0, 1] * 50
Import shuffle
from random
从
random
导入shuffle
>>> from random import shuffle
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.