3 回答
TA贡献1805条经验 获得超10个赞
当您获得第 7 次正面或反面重复时,应将其计为连续,因为最后 6 次翻转确实形成了连续。通过在 6 之后重置计数,您低估了条纹的数量。
从概率的角度来看,您打印的结果不是“机会”的度量(永远不会超过 100%),而是更接近数学期望(即期望值的总和乘以它们各自的概率)。您的代码会生成实际尝试的样本,但计算没有意义,除非它们可以与适当的概率数字进行比较。
以下是我将如何实现此采样并表达结果:
import random
from itertools import accumulate
expCount = 10000
expSize = 100
streakSize = 6
numberOfStreaks = 0
for experimentNumber in range(expCount):
results = [random.choice("HT") for _ in range(expSize)]
consec = [int(a==b) for a,b in zip(results,results[1:])]
streaks = sum( s+1>=streakSize for s in accumulate(consec,lambda s,m:s*m+m))
numberOfStreaks += streaks
ratio = numberOfStreaks / expCount
print(f'Obtained {numberOfStreaks} streaks of {streakSize} head/tail on {expCount} runs of {expSize} flips. On average {ratio:.2f} streaks per run')
TA贡献1856条经验 获得超17个赞
import random
numberOfStreaks = 0
numberOfExperiments = 10000
numberOfAttemps = 100
for experimentNumber in range(numberOfExperiments):
# Code that creates a list of {numberOfAttemps} 'heads' or 'tails' values.
coinFlip = []
for i in range(numberOfAttemps):
if random.randint(0, 1) == 0:
coinFlip.append("H")
else:
coinFlip.append("T")
# Code that checks if there is a streak of 6 heads or tails in a row.
for i in range(len(coinFlip)):
if (["H"] * 6) in [coinFlip[i:i+6]] or (["T"] * 6) in [coinFlip[i:i+6]]:
numberOfStreaks += 1
for n in range(5):
coinFlip.pop(i)
print('Chance of streak: %s%%' % (numberOfStreaks / numberOfExperiments))
输出:
Chance of streak: 1.5143%
TA贡献1784条经验 获得超7个赞
import random, time
numberOfStreaks = 0
for experimentNumber in range(10000):
# Code that creates a list of 100 'heads' or 'tails' values.
List = []
for value in range(100):
value = random.randint(0,1)
if value == 0:
List.append('H')
if value == 1:
List.append('T')
# print('List = ', end=' ')
# print(List)
# Code that checks if there is a streak of 6 heads or tails in a row.
sixStreakHeads = 0
sixStreakTails = 0
for result in range(len(List)):
if List[result] == 'H':
sixStreakHeads += 1
sixStreakTails = 0
if sixStreakHeads == 6:
sixStreakHeads = 0
numberOfStreaks += 1
if List[result] == 'T':
sixStreakTails += 1
sixStreakHeads = 0
if sixStreakTails == 6:
sixStreakTails = 0
numberOfStreaks += 1
# print('Six Streak Heads: ', sixStreakHeads)
# print('Six Streak Tails: ', sixStreakTails)
# time.sleep(.5)
# print('\n\n\n')
print('Chance of streak: ', numberOfStreaks / 10000 * 100, '%')
添加回答
举报