import random weights = [(0,0.08),(1,0.51),(2,0.51)] results = [] def weighted_choice(choices): total = sum(w for c, w in choices) r = random.uniform(0, total) upto = 0 for c, w in choices: if upto + w > r: return c upto += w assert False, "Shouldn't get here" for x in range(1000): rolls = [] while True: rolls.append(weighted_choice(weights)) if len(set(rolls)) == 3: results.append(len(rolls)) break print "Mean:\t %.2f" % (float(sum(results))/len(results)) prob = dict() for num in results: prob[num] = prob.get(num,0) + 1 for num, tot in prob.items(): perc = (float(tot)/len(results)) * 100 prob[num] = perc cumprob = 0 for num, perc in prob.items(): cumprob += perc print "%d:\t%.2f" % (num, cumprob)
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