Search code examples
python-3.xalgorithmrandomprobability

Is there a shorter version, biased probability?


import random as rd
def prob(times):
    h,t=0,0
    for _ in range(times):
        if rd.randrange(1,11)<=7:h+=1
        else:t+=1
    return h

To return the results of biased coin flipping 70% head


Solution

  • As you only return h, you don't actually need t. It is also not needed to use randrange -- you can achieve the same with random.

    For the actual counting you can use sum, and the boolean result can be converted to 0 or 1 with int:

    def prob(times):
        return sum(int(rd.random() < 0.7) for _ in range(times))
    

    Or in lambda notation:

    prob = lambda times: sum(int(rd.random() < 0.7) for _ in range(times))