pythonstatisticsprobabilitymontecarlocoin-flipping

Trying to generate a conditional coin flip


So I'm a trying to create a function which first flips an unbiased coin but if the result is heads it flips a biased coin with 0.75 probability of heads. If it shows tails then the next flip is unbiased. I've tried the following code but I can only run this flow once i.e., if it's a head, then only the next one flip is biased and then the flow is returning to the top of the 'for' loop. Is there any recursion that I can do which can keep it inside the loop?

def prob1():
    choices = []
    for _ in range (1,501):
        x = random.choice(Toss_list)
        if x == 0:
            y = random.choices(Toss_list, weights=(0.75,0.25))
        else:
            y = random.choices(Toss_list, weights=(1,1))
        choices.append(x)
        choices.append(y)
    heads = choices.count([0])+choices.count(0)
    tails = choices.count([1])+choices.count(1)
    return print(f'Count of heads = {heads} and count of tails = {tails}' )


Solution

  • From what I understand, the biasing only depend on the previous choice.
    I would simplify the code with this:

    import random
    tossList = ['H', 'T']
    choice = 'T'   # first choice will be unbiased
    heads,tails = 0,0
    for _ in range(500):
      weights = (0.5, 0.5) if choice == 'T' else (0.75, 0.25)
      choice = random.choices( tossList, weights)
      if choice == ['H']:
        heads += 1 
      else:
        tails += 1
    print( f'Count of heads = {heads} and count of tails = {tails}' )