python 尝试进行有条件的抛硬币

zpjtge22  于 2022-10-30  发布在  Python
关注(0)|答案(3)|浏览(117)

所以,我尝试创建一个函数,它首先掷出一个无偏硬币,但如果结果是正面,它会以0.75的概率掷出一个有偏硬币。如果结果是反面,那么下一次掷出的硬币是无偏的。我尝试了下面的代码,但我只能运行一次这个流程。即,如果结果是正面,那么只有下一个翻转是偏置的,然后流返回到'for'循环的顶部.有没有什么递归可以让它保持在循环内部?

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

vkc1a9a21#

据我所知,这种偏向只取决于先前的选择。
我将使用以下代码简化代码:

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

7hiiyaii2#

您可以将其置于无限循环中,例如

While True:

# Do code here

或者


# Exsample:

tosses = 1
while tosses <= 10: 
   print(tosses )
   tosses += 1
72qzrwbm

72qzrwbm3#

您可以尝试以下操作:

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

相关问题