Trying to generate a conditional coin flip

Question:

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}' )

Asked By: Arhaan Shaikh

||

Answers:

You can put it in a infinite loop such as

While True:
#Do code here

Or

#Exsample:
tosses = 1
while tosses <= 10: 
   print(tosses )
   tosses += 1
Answered By: Topepe

You can try this:

import random

def prob1():
    choices = []
    biased_flag = 0
    for _ in range (1,501):
        x = random.choices(Toss_list, weights=(0.75,0.25)) if biased_flag else random.choice(Toss_list)
        if x == 0 and biased_flag == 0:
            biased_flag = 1
        # implement other rules that decide the coin to use for the next toss
        choices.append(x)

    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}' )
Answered By: Swifty

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}' )
Answered By: user3435121