Get a Random Boolean by percentage
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Future Grid Looping
--
Chapters
00:00 Get A Random Boolean By Percentage
00:39 Accepted Answer Score 28
01:05 Answer 2 Score 2
01:15 Answer 3 Score 1
01:39 Answer 4 Score 0
01:53 Thank you
--
Full question
https://stackoverflow.com/questions/1432...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #random #python27
#avk47
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Future Grid Looping
--
Chapters
00:00 Get A Random Boolean By Percentage
00:39 Accepted Answer Score 28
01:05 Answer 2 Score 2
01:15 Answer 3 Score 1
01:39 Answer 4 Score 0
01:53 Thank you
--
Full question
https://stackoverflow.com/questions/1432...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #random #python27
#avk47
ACCEPTED ANSWER
Score 28
Just return the test:
def reset(percent=50):
return random.randrange(100) < percent
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 True to be returned for a given percentage; if percent = 100 then you want True all of the time, e.g. when all values that randrange() produces are below the percent value.
ANSWER 2
Score 2
How about:
def reset(percent=50):
return random.randrange(0, 100) > percent
ANSWER 3
Score 1
@rjbez You asked for a function which returns true in X percentage of time. When X == 0% it should always return false. When X == 100% it should always return true. The current accepted answer is now fixed and has the proper relation
def reset(percent=50):
return random.randrange(100) < percent
ANSWER 4
Score 0
Just use PyProbs library. It is very easy to use.
>>> from PyProbs import Probability as pr
>>>
>>> # You can pass float (i.e. 0.5, 0.157), int (i.e. 1, 0) or str (i.e. '60%', '3/11')
>>> pr.Prob('50%')
False
>>> pr.Prob('50%', num=5)
[False, False, False, True, False]