【问题标题】:Python program that rolls a fair die counts the number of rolls before a 6 shows up掷骰子的 Python 程序计算出现 6 之前的掷骰数
【发布时间】:2019-03-04 23:15:54
【问题描述】:
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

谢谢

【问题讨论】:

  • 是的,这是这个计算的合理解决方案,是的,它应该输出大约 0.83 (5/6)。
  • @PM2Ring 是的,我现在已经编辑了代码。
  • final = (counter2)/(sample_size) 没有正确缩进。如果不使用变量“final”,它的目的是什么。你在哪里定义和初始化expect
  • @yoonghm 它应该是“最终的”(存储在出现 1 之前所用的滚动数总和的变量)而不是“期望”。道歉。
  • 你能解释一下final = (counter2)/(sample_size)的逻辑吗?

标签: python python-3.x probability dice


【解决方案1】:

坚持您的概念,我将创建一个包含每个卷的列表,然后使用 enumerate 计算每个 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

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

      猜你喜欢
      • 2014-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 2018-09-08
      • 2017-11-06
      • 2021-03-12
      相关资源
      最近更新 更多