本文介绍了掷出公平骰子的 Python 程序会在 6 出现之前计算掷出的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随机导入sample_size = int(input("请输入您希望我掷骰子的次数:"))如果 (sample_size 

这里使用的逻辑是否正确?它将重复掷骰子,直到掷出一个骰子,同时跟踪在一个骰子出现之前所花费的掷骰次数.当我为高值(500+)运行它时,它给出的值为 0.85

谢谢

解决方案

坚持你的概念,我会创建一个包含每个卷的列表,然后使用 enumerate 来计算每个 1 之间的索引数量并总结这些,使用索引作为标记.

存储在 1 出现之前所花费的滚动次数总和的变量 - OP

from random import randint样本大小 = 0而 sample_size 
输入卷数:10[5, 3, 2, 6, 2, 3, 1, 3, 1, 1]70.7

相同尺寸 500:

输入卷数:5004060.812

import random

sample_size = int(input("Enter the number of times you want me to roll the die: "))

if (sample_size <=0):

    print("Please enter a positive number!")

else:
    counter1 = 0

    counter2 = 0

    final = 0

    while (counter1<= sample_size):

        dice_value = random.randint(1,6)

        if ((dice_value) == 6):
            counter1 += 1

        else:
            counter2 +=1

    final = (counter2)/(sample_size)  # fixing indention


print("Estimation of the expected number of rolls before pigging out: " + str(final))

Is the logic used here correct? It will repeat rolling a die till a one is rolled, while keeping track of the number of rolls it took before a one showed up. It gives a value of 0.85 when I run it for high values(500+)

Thanks

解决方案

Sticking with your concept, I would create a list that contains each roll then use enumerate to count the amount of indices between each 1 and sum those, using the indicies as markers.

the variable that stores the sum of the number of rolls it took before a 1 showed up - OP

from random import randint

sample_size = 0
while sample_size <= 0:
    sample_size = int(input('Enter amount of rolls: '))

l = [randint(1, 6) for i in range(sample_size)]

start = 0
count = 0

for idx, item in enumerate(l):
    if item == 1:
        count += idx - start
        start = idx + 1

print(l)
print(count)
print(count/sample_size)

Sameple Size 500:

这篇关于掷出公平骰子的 Python 程序会在 6 出现之前计算掷出的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 16:20