Get a Random Boolean by percentage
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2
--
Chapters
00:00 Question
00:49 Accepted answer (Score 25)
01:26 Answer 2 (Score 2)
01:38 Answer 3 (Score 1)
02:10 Answer 4 (Score 0)
02:28 Thank you
--
Full question
https://stackoverflow.com/questions/1432...
Answer 3 links:
[PyProbs]: https://pypi.org/project/pyprobs/
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #random #python27
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2
--
Chapters
00:00 Question
00:49 Accepted answer (Score 25)
01:26 Answer 2 (Score 2)
01:38 Answer 3 (Score 1)
02:10 Answer 4 (Score 0)
02:28 Thank you
--
Full question
https://stackoverflow.com/questions/1432...
Answer 3 links:
[PyProbs]: https://pypi.org/project/pyprobs/
--
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]