[面试题] 等概率生成器

题目:已知一随机发生器,产生0的概率是p,产生1的概率是1-p,现在要你构造一个发生器,使得它构造0和1的概率均为1/2;

import random
p = 200
def generate(p):
    n = random.randrange(0, 1000)
    res = 0
    if n > p:
        return 0
    else:
        return 1

def generate_01(): # 生成 0 和 1 等概率
    n1 = generate(p)
    n2 = generate(p)
    if (n1 == 0 and n2 == 1):
        return 1
    if (n1 == 1 and n2 == 0):
        return 0
    return generate_01()

l1 = 0
l0 = 0
for i in range(1000):
    x = generate_01()
    if x == 1:
        l1 += 1
    if x == 0:
        l0 += 1

print("l0:", l0)
print("l1", l1)
  

  

posted @ 2021-10-27 08:53  算是一个初学者  阅读(44)  评论(0编辑  收藏  举报