Python硬币翻转条纹

2024-06-25 22:49:50 发布

您现在位置:Python中文网/ 问答频道 /正文

目标是将python代码编写到:

(1)模拟10000次抛硬币,并在列表中记录正面(H)和反面(T)值。我在下面的代码中将其命名为expList。 (2) 计算6个头部或6个尾部连续出现的条纹数,然后计算条纹占总翻转的百分比

以下代码中是否有错误:

import random

numberOfStreaks = 0
expList = []

for expNumber in range(10000):
    if random.randint(0,1)==0:
        expList.append('H')
    else:
        expList.append('T')

for i in range(len(expList)-5):
    if expList[i] == 'T' and expList[(i+1)]=='T' and expList[(i+2)]=='T' and expList[(i+3)]=='T' and expList[(i+4)]=='T' and expList[(i+5)]=='T':
        numberOfStreaks+=1
    elif expList[i] == 'H' and expList[(i+1)]=='H' and expList[(i+2)]=='H' and expList[(i+3)]=='H' and expList[(i+4)]=='H' and expList[(i+5)]=='H':
        numberOfStreaks+=1

print(numberOfStreaks)
print(f'Chances of streak : {numberOfStreaks*100/10000}')

当我尝试不同的翻转次数(比如100000或1000次,而不是10000次)时,我得到了各种各样的概率百分比


Tags: and代码in目标forifrange硬币
2条回答

我的业余尝试:

# Coin Flip Streaks


import random

streaks=0
total=10 # Simplifying calculations
reps=10

for experimentNumber in range(total):
    coin_flips=[] # You must reset the coin_flips list. Your program keeps appending values to ur list without deleting the old ones.

    for j in range(reps):
        coin_flips.append(random.choice(['H','T']))

    repetition=1 # any flip is a streak of at least 1
    for i in range(1,len(coin_flips)):
        if coin_flips[i]== coin_flips[i-1]:
            repetition+=1
        else:
            repetition=1
        if repetition==4:
            streaks+=1
            break

    print(coin_flips) 


total_strks=(reps//4)*total # calculating the total num of strks within all lists 

streaks_per=100*streaks/total_strks # calculating the percent of strks

print('Chance of streak: %s%%' % (streaks_per))
print(f'{streaks} of {total_strks}') # In order to test the streaks' counter

如果我错过了什么,请告诉我

是,您的代码包含错误。
考虑一个例子,当7头或7尾出现在一行。根据您的代码,此条件将被计数两次。

[H'、'H'、'H'、'H'、'H'、'H'、'H'、'H']

i=0时会发生一次计数,i=1时会发生另一次计数,其中i表示列表的索引

相关问题 更多 >