python-3.x - 自动化无聊的事情 - 硬币翻转条纹

标签 python-3.x statistics coin-flipping

我知道现在有很多关于它的问题,即使是同一个问题,但我想我尝试了一些不同的方法。

任务是获取 10.000 个样本,每个样本翻转 100 次,然后计算所有样本出现 6 次正面或反面条纹的概率 - 据我所知。但是在之前的问题中,编码问题被描述为有点模糊。因此,如果你们能指出代码中的错误,那就太好了:)

我试着尽可能地懒惰,这导致我的 macbook 工作非常努力。这是我的代码。当前值与之前值的比较的第一次迭代是否有问题(据我所知,我会将索引 -1(然后是索引 100?)与当前值进行比较?)

import random

#variable declaration

numberOfStreaks = 0
CoinFlip = []
streak = 0

for experimentNumber in range(10000):
    # Code that creates a list of 100 'heads' or 'tails' values.
    for i in range(100):
        CoinFlip.append(random.randint(0,1))
    #does not matter if it is 0 or 1, H or T, peas or lentils. I am going to check if there is multiple 0 or 1 in a row        

    # Code that checks if there is a streak of 6 heads or tails in a row.
    for i in range(len(CoinFlip)):
        if CoinFlip[i] == CoinFlip[i-1]:  #checks if current list item is the same as before
            streak += 1 
        else:
            streak = 0

        if streak == 6:
            numberOfStreaks += 1

print('Chance of streak: %s%%' % (numberOfStreaks / 100))

我哪里弄得一团糟?我真的看不出来!

最佳答案

您需要重置 CoinFlip 列表。您当前的程序只是不断地附加到 CoinFlip,这使得列表非常长。这就是你的表现不好的原因。我还添加了一个 i==0 的检查,这样您就不会与列表的末尾进行比较,因为从技术上讲,这不是连胜的一部分。

for experimentNumber in range(10000):
    # Code that creates a list of 100 'heads' or 'tails' values.
    for i in range(100):
        CoinFlip.append(random.randint(0,1))
    #does not matter if it is 0 or 1, H or T, peas or lentils. I am going to check if there is multiple 0 or 1 in a row

    # Code that checks if there is a streak of 6 heads or tails in a row.
    for i in range(len(CoinFlip)):
        if i==0:
            pass
        elif CoinFlip[i] == CoinFlip[i-1]:  #checks if current list item is the same as before
            streak += 1
        else:
            streak = 0

        if streak == 6:
            numberOfStreaks += 1

    CoinFlip = []

print('Chance of streak: %s%%' % (numberOfStreaks / (100*10000)))

我还认为您需要除以 100*10000 才能得到真正的概率。我不确定为什么他们的 "hint"建议仅除以 100。

关于python-3.x - 自动化无聊的事情 - 硬币翻转条纹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60658830/

相关文章:

python - 确定跨行的唯一字典键

Python 3 : setup. py:执行所有操作的 pip 安装 (build_ext + install)

java - 这些方向我不清楚

python-3.x - 用 Python 模拟 10,000 次硬币翻转非常慢

python - 如何使 OpenGL 镜面光工作?

python - Python中的异常(多个try block )

c# - .NET 的最佳 NoSQL DB 来存储大量带有时间索引的分钟统计数据?

c# - 如何得到多次执行伯努利实验的详细结果(概率树)

python - 如何模拟有偏硬币的翻转?