【发布时间】:2020-07-30 07:26:14
【问题描述】:
我试图编写一个程序来找出在随机生成的正面和反面列表中出现六个正面或六个反面的频率,但我的结果很荒谬(我得到了 150% 而其他人大约 80%)。我试图将我的程序与其他程序进行比较,但始终不明白我哪里出错了。你能告诉我有什么问题吗?
import random
TotalStreaks = 0
for experimentNumber in range(10000):
# Code that creates a list of 100 'heads' or 'tails' values.
explist = []
numberOfStreaks = 0
for value in range(100):
if random.randint(0,1) == 0:
explist.append('H')
else:
explist.append('T')
# Code that checks if there is a streak of 6 heads or tails in a row.
for i in range(95): #we are comparing the value of the next 5 values so we want the range to be 100-5
#compare the element i with the next five elements to see if they match
if explist[i] == explist[i+1] == explist[i+2] == explist[i+3] == explist[i+4] == explist[i+5]:
#see if it's the first streak (a.k.a. numberOfStreaks == 0) or
#if i is not equal to the 5 indexes that follow the most recent index of a streak
if numberOfStreaks == 0 or i not in rep:
numberOfStreaks+=1
#rep is the list of the indexes of the 5 numbers following the number i
#which is where the streak was identified
rep = [i+1, i+2, i+3, i+4, i+5]
TotalStreaks += numberOfStreaks
print('Chance of streak: %s%%' % ((TotalStreaks / 10000) * 100))
【问题讨论】:
-
为什么不在列表中使用
0和1而不是H和T?这样,sum(explist[i:i+6])等于 0 或 6 会告诉您它是全 0 还是全 1。还有一个定义问题。THHHHHHHT是连续6个头还是连续7个头? -
您的代码基本上是正确的,但您计算的是系列中的平均条纹数(大约为 1.5)。只有当你乘以 100% 并将其描述为概率时,问题才会出现。
-
@JohnColeman 你是对的,我可以使用 0 和 1(这是我的错误,它会节省代码行),但是总结 6 个连续值似乎不是一个好主意,因为如果我碰巧有 8 个连续的尾巴,我最终会考虑 3 个条纹,而实际上我只有 1 个。
-
将其编辑到问题中会很好。顺便说一句,我自己写的,得到了大约 81%。
-
@AnaFerreira
import re, random; sum(bool(re.search(r'(.)\1{5}', ''.join(random.choices('HT', k=100)))) for _ in range(10000)) / 100
标签: python probability