掷出合理骰子的Python程序会在出现6之前计数掷骰数

时间:2018-09-29 00:42:48

标签: python python-3.x probability dice

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))

这里使用的逻辑是否正确?它将重复滚动模具直到滚动一个模具,同时跟踪一个模具出现之前所花费的辊数。当我为高值(500+)运行它时,它的值为0.85

谢谢

2 个答案:

答案 0 :(得分:0)

import random

while True:
  sample_size = int(input("Enter the number of times you want me to roll a die: "))
  if sample_size > 0:
    break

roll_with_6 = 0
roll_count = 0

while roll_count < sample_size:
  roll_count += 1
  n = random.randint(1, 6)
  #print(n)
  if n == 6:
    roll_with_6 += 1

print(f'Probability to get a 6 is = {roll_with_6/roll_count}')

一个示例输出:

Enter the number of times you want me to roll a dile: 10
Probability to get a 6 is = 0.2

另一个示例输出:

Enter the number of times you want me to roll a die: 1000000
Probability to get a 6 is = 0.167414

答案 1 :(得分:0)

根据您的概念,我将创建一个包含每个卷的列表,然后使用枚举计数每个1之间的索引数量,并使用索引作为标记对这些索引求和。

该变量存储在 1 出现之前所花费的总卷数-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)
Enter amount of rolls: 10
[5, 3, 2, 6, 2, 3, 1, 3, 1, 1]
7
0.7

相同尺寸500:

Enter amount of rolls: 500
406
0.812