from random import uniform
prob = [0.25,0.30,0.45]
def onetrial(prob):
u=uniform(0,1)
if 0 < u <= prob[0]:
return 11
if prob[0] < u <= prob[0]+prob[1]:
return 23
if prob[0]+prob[1] < u <= prob[0]+prob[1]+prob[2]:
return 39
print onetrial(prob)
I wonder how to reduce the repetitive part in the def using some for-loop techniques. Thanks.
Assuming you call
onetrialfrequently, calculate the CDF first to make it a bit faster:You could use bisect to make it even faster.