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.
關(guān)鍵是要找到一種情形眉枕,使得0和1的概率相同驯妄。有一種情形是履植,連續(xù)兩次扔foo(),那出現(xiàn)01和出現(xiàn)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()