Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Pearls in the Box by cbrunet
def checkio(marbles, step):
"""Probability of drawing white pearl in step steps."""
n = len(marbles) # number of marbles
b = sum(1 for m in marbles if m == 'b') # number of black marbles
w = n - b # number of white marbles
pw = w / n # probability of drawing white marble
pb = 1 - pw # probability of drawing black marble
if step > 1: # end when step == 1
if w > 0:
# white branch
pw = pw * checkio('w' * (w-1) + 'b' * (b+1), step-1)
if b > 0:
# black branch
pb = pb * checkio('w' * (w+1) + 'b' * (b-1), step-1)
pw += pb
return pw
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
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"
Feb. 13, 2014
Comments: