首页 > 解决方案 > Python - 硬币翻转条纹

问题描述

目标是将python代码编写到:

(1) 模拟 10,000 次抛硬币,并将 Heads(H) 和 Tails(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,而不是 10,000)时,我得到的概率百分比真的不同

标签: python

解决方案


是的,您的代码包含错误。
考虑一个连续出现 7 个正面或 7 个反面的例子。根据您的代码,此条件将被计算两次。

['H','H','H','H','H','H','H']

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


推荐阅读