使用Python 2.7。假设我有一个不公平的硬币,我想用下面的方式把它变成一个公平的硬币,
不确定此方法是否有效?实际上我对上面的方法以及如何正确使用equalCoinHelper()
并不是很有信心(我在我的代码中标记了我的问题)。
如果有人有任何好的想法,那就太好了。
from __future__ import print_function
import random
counter = 0
# 0.3 probability return head as 1
# 0.7 probability return tail as 0
def unFairCoin():
if random.random() < 0.3:
return 1
else:
return 0
# probability of generating 1 is equal, so keep 1 only
def equalCoinHelper():
result = 0
while result == 0:
result = unFairCoin()
def equalDistribution():
global counter
# not think about how to leverage this better
equalCoinHelper()
counter += 1
if counter % 2 == 0:
return 1
else:
return 0
if __name__ == "__main__":
# generate 10 random 0/1 with equal probability
print ([equalDistribution() for _ in range(10)])
答案 0 :(得分:3)
Getting a Fair Toss From a Biased Coin解释了一种将有偏见的硬币变成公平硬币的简单算法:
在Python中,这将是:
def fairCoin():
coin1 = unfairCoin()
coin2 = unfairCoin()
if coin1 == coin2:
return fairCoin() # both are the same, so repeat it
elif coin1 == 1 and coin2 == 0:
return 1
else:
return 0
elif
和else
块可以简化为:
else:
return coin1
答案 1 :(得分:2)
@ Barmar的答案的另一种实现方式,即避免递归调用(即使它可能是无害的)
def fairCoin():
coin1 = 0
coin2 = 0
while coin1 == coin2:
coin1 = unfairCoin()
coin2 = unfairCoin()
return coin1