python - 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)时,我得到的概率百分比真的不同
解决方案
是的,您的代码包含错误。
考虑一个连续出现 7 个正面或 7 个反面的例子。根据您的代码,此条件将被计算两次。
['H','H','H','H','H','H','H']
i = 0 将发生一次计数,i = 1 将发生另一个计数,其中 i 表示列表的索引.
推荐阅读
- android - 云数据库 AGConnectInitializeProvider 错误
- node.js - Facebook API,创建创意错误无法加载帖子
- c# - 在 C# 中查找给定的 2 个字符串数组中的位置和差异项
- c++ - 如果功能已经启动,我该如何停止?
- java - 如何解决,非法尝试将非集合映射为 @OneToMany、@ManyToMany 或 @CollectionOfElements
- amazon-web-services - Is there a way to conditionally add expiration policies to an S3 bucket in cloudformation
- python - 我正在尝试在 python 上使用 smtplib 和 ssl 发送电子邮件,但我不断收到 TupeError: __init__() got an unexpected keyword argument 'context'
- visual-studio-code - VSC 中的 CSSComb 不能与 :root 选择器一起使用
- c# - 子元素不想移动
- mysql - 如何在 codeigniter 中使用数组值创建超过 1 个子句