How can I speed up my calculations with loops? Python
The code is very hard to follow. Here's a possible refactor to make its intent
clearer. Some key ideas in the simplification: (1) use loops to manage counters
rather than manually incrementing/decrementing; (2) use more
meaningful variable names when context isn't clear; and (3) delegate some of
the complexity to a helper function. The third idea is the most impactful: the
helper function is simple because it does so little; and the main function,
having been relieved of a burden, is simpler as well -- so simple, in
fact, that it boils down to computing a sum over two loops.
def math_count(inv, trials = 10000):
    total_attempts = sum(
        attempts_to_get_lte(x)
        for _ in range(trials, 0, -1)
        for x in range(inv, 0, -1)
    )
    return total_attempts / trials

def attempts_to_get_lte(x):
    attempts = 0
    while True:
        attempts += 1
        if random.randint(1, 45) &lt;= x:
            return attempts

But attempts_to_get_lte() is an easily solved probability problem: rather
than have Python simulate the manual flipping of coins, we can just do a little
math. If you prefer that approach, I believe the following is correct
(probability experts should chime in if I've gone astray):
def math_count_exact(inv):
    return sum(45 / x for x in range(inv, 0, -1))