You are given a function foo() that represents a biased coin. When foo() is called, it returns 0 with p probability, and 1 with 1-p probability. Write a new function that returns 0 and 1 with 50% probability each. Your function should use only foo(), no other library method.
关键是要找到一种情形,使得0和1的概率相同。有一种情形是,连续两次扔foo(),那出现01和出现10的概率是相同的,为p(1-p) = (1-p)p。
def foo():
def Fair_from_biased():
first = foo()
second = foo()
if first == 0 and second == 1:
return 0
elif first == 1 and second == 0:
return 1
else:
return Fair_from_biased()