Python程序在掷骰子6之前计算掷骰子的次数

2024-09-27 07:24:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

谢谢


Tags: ofthesamplenumbersizeifvaluerandom
2条回答

按照您的概念,我将创建一个包含每个滚动的列表,然后使用enumerate来计算每个1之间的索引数量,并将这些索引作为标记进行相加。在

存储a1出现前所用转鼓数总和的变量-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
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}')

一个样本输出:

^{pr2}$

另一个示例输出:

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

相关问题 更多 >

    热门问题