I had to simulate a biased die such that 6 occurs more than 50% of the times. Which I was able to do using:
from random import randint,choice
def bdie():
out = random.randint(0,2)
if (out==1 or out == 2):
return 6
else:
r = choice([i for i in range(1,7) if i not in [6]])
return r
def bdthrow(n):
output = []
for i in range(0,n):
if n>0 & n<=100000000:
outcome = bdie()
output.append(outcome)
else:
print("Invalid")
print(output)
For which the output would be:
[6, 6, 6, 6, 6, 3, 6, 3, 5, 4]
Now on this biased die I am supposed to find the probability of top face being 5 and I need to find the average count of each face of the die.
Now solving the sum on a paper is easy where I can find the probability but I'm not sure how to implement this in python.
If I understand correctly you are looking for an unbiased estimator of getting 5. Such an estimator can be the number of 5 obtains when throwing the dice enough times. I.e # fives / n
.
From memory perspective I would recommend using defaultdict
. Also there is no need to check the value of n
on every round.
from random import randint,choice
from collections import defaultdict
def bdie():
out = randint(0,2)
if (out==1 or out == 2):
return 6
else:
r = choice([i for i in range(1,7) if i not in [6]])
return r
def bdthrow(n):
output = defaultdict(int)
for i in range(0,n):
outcome = bdie()
output[outcome] +=1
return (float(output[5])/n)
There are few other optimisations to the code but naively that should work.