I wrote this code. But it works very slowly.
I'm figuring out how many times I have to run the case generator to find numbers less than or equal to inv, in this case six. I count the number of attempts until a digit <= 6 is generated. I find inv equal to 1 and repeat the loop. Until inv is 0. I will keep trying to generate six digits <= 6.
And I will repeat all this 10 ** 4 degrees again to find the arithmetic mean.
Help me speed up this code. Works extremely slowly. The solution should be without third-party modules. I would be immensely grateful. Thank!
import random
inv = 6
def math_count(inv):
n = 10**4
counter = 0
while n != 0:
invers = inv
count = 0
while invers > 0:
count += 1
random_digit = random.randint(1, 45)
if random_digit <= invers:
invers -= 1
counter += count
count = 0
if invers == 0:
n -= 1
invers = inv
return print(counter/10**4)
math_count(inv)
def math_count(inv, trials = 10000): return sum(attempts_to_get_lte(x) for n in range(trials, 0, -1) for x in range(inv, 0, -1)) / trials
, wheretrials = 10000
andattempts_to_get_lte()
is a simple function that computes how many attempts are needed untilrandom.randint(1, 45) <= x
. So, one answer to the OP's question is Use fewer trials for the estimate. Another answer, as you note, is Use math to get the answer immediately. \$\endgroup\$