'optimally check combination of two random numbers and count occurs if they pass condition
I would like to do a check of two value's random combination, that passes certain condition. I constructed a snippet, that somehow works:
from random import random
i, n = 0, 100
for _ in range(n):
x = random()
y = random()
if x >= 0.5 and y >= 0.5:
i += 1
But I feel like I can approach more efficiently here (ie. the variables i, x, y could be somehow omitted). I was even thinking that list comprehension could improve it more, but I must admit during creation of this one, I totally failed.
My closest approach was something like:
[lambda x,y: [random(), random()] for _ in range(n) if x >= 0.5 and y >= 0.5 ]
That unfortunately creates 100 occurrences - it looks like condition is not applied onto my x, y variables.
As it looks like I'm still a python beginner, can someone advise me, how to do it the most efficient way (smallest footprint would be the key decision here).
Solution 1:[1]
Use the sum() function.
i = sum(random() >= 0.5 and random() >= 0.5 for _ in range(n))
Booleans can be treated as integers, where True == 1 and False == 0, so the sum will be correct.
Solution 2:[2]
You make the accepted answer faster by using the fact that you don't need to generate two random numbers and can instead combine their probabilities:
p_1 = 0.5
p_2 = 0.5
p_combined = 1-(1-p_1)*(1-p_2)
sum(random() >= p_combined for _ in range(n))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Nin17 |
