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 colinmcnicholl
from itertools import product
def checkio(marbles, step):
"""input: The start sequence of the marbles as a string and the step number as an integer.
output: The probability for a white marble as a float."""
def calc_prob(binary_choice):
"""Computes the probability of choosing a marble of a given colour out of the box.
e.g. box contains 'bbw' - probability of choosing a white marble is 1/3.
probability of choosing a black marble is 1 - (1/3) = 2/3."""
num_white = marbles.count('w')
denominator = len(marbles)
# Keep track of probability.
multiplier = 1
for choice in binary_choice:
if choice == 'w':
# Update probability at each new choice.
multiplier *= num_white / denominator
num_white -= 1
else:
multiplier *= 1 - num_white / denominator
num_white += 1
# The probability of a white marble at the Nth step.
return multiplier * (num_white / denominator)
# Call calc_prob on each of the possible sequence of choices leading to (N-1)th step.
possible_choices = product(['b', 'w'], repeat = step - 1)
return round(sum(calc_prob(choices) for choices in possible_choices), 2)
#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"
Oct. 6, 2017