Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Recursion solution in Clear category for Pearls in the Box by Krischtopp
def checkio(marbles: str, step: int) -> float:
return round(prob(marbles.count('b'), marbles.count('w'), step), 2)
def prob(black: int, white: int, step: int, prob_so_far: float=1.0) -> float:
if step <= 1: # last step, calculate probability of winning
return prob_so_far * white / (black + white)
if black < 0 or white < 0: # invalid step, took too many black/white pearls
return 0
'''
Steps into recursion:
1st line: remove one black pearl, put in one white pearl, calculate probability of winning
2nd line: put in one black pearl, remove one white pearl, calculate probability of winning
Add both results (the probabilities of all last turns) and return to the calling method
'''
return prob(black - 1, white + 1, step - 1, prob_so_far * black / (black + white)) + \
prob(black + 1, white - 1, step - 1, prob_so_far * white / (black + white))
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
print("Example:")
print(checkio('bbw', 3))
assert checkio('bbw', 3) == 0.48, "1st example"
assert checkio('wwb', 3) == 0.52, "2nd example"
assert checkio('www', 3) == 0.56, "3rd example"
assert checkio('bbbb', 1) == 0, "4th example"
assert checkio('wwbb', 4) == 0.5, "5th example"
assert checkio('bwbwbwb', 5) == 0.48, "6th example"
print("Coding complete? Click 'Check' to earn cool rewards!")
Feb. 7, 2020