I’m trying to get a get a random boolean but with a weighted percentage. For instance, I want the user to pass in a percentage (i.e. 60) and the generator will randomly select true 60% of the time.
What I have is this:
def reset(percent=50):
prob = random.randrange(0,100)
if prob > percent:
return True
else:
return False
Is there a better way to do this? This seems inefficient and cumbersome. I don’t need it to be perfect since it is just used to simulate data, but I need this to be as fast as possible.
I’ve searched (Google/SO) and have not found any other questions for this.
Just return the test:
because the result of a
<lower than operator is already a boolean. You do not need to give a starting value either.Note that you need to use lower than if you want
Trueto be returned for a given percentage; ifpercent = 100then you wantTrueall of the time, e.g. when all values thatrandrange()produces are below thepercentvalue.