import random candies = ['M', 'M', '&', 'T', 'T', 'T', 'T', 'T', 'T', 'T'] # set probabilities to 20% M, 10% & def trial(probs): collect = {'M':0, '&':0, 'T':0} # Create counters for each possibility while collect['M'] < 2 or collect['&'] < 1: # Keep going until you have 2 'M's and an '&' collect[random.choice(probs)] += 1 # Get a random bag, tally its tile return sum(collect.values()) # Return the number of total bags before success def repeat_trial(probs, trial_num): total = sum(trial(probs) for x in range(trial_num)) # Add up the results of all the trials return float(total) / trial_num # Divide by the number of trials to get an average print repeat_trial(candies, 100000) # Run the functions and print the result # Note: Different similar problems can be easily run by changing the candies list or making a new list.
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question