掷骰子的Python程序在掷骰子6之前计算掷骰子的数量 随机导入 sample_size=int(输入(“输入希望我滚动模具的次数:”) 如果(样本大小)
另一个示例输出:掷骰子的Python程序在掷骰子6之前计算掷骰子的数量 随机导入 sample_size=int(输入(“输入希望我滚动模具的次数:”) 如果(样本大小),python,python-3.x,probability,dice,Python,Python 3.x,Probability,Dice,另一个示例输出: 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 = ran
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
按照您的概念,我将创建一个包含每个卷的列表,然后使用enumerate计算每个
1
之间的索引数量,并将这些索引相加,使用标记作为标记
存储1出现之前的转鼓数总和的变量-OP
Sameple尺寸500:
是的,这是这个计算的合理解决方案,是的,它应该输出0.83(5/6)左右。@PM2Ring是的,我现在已经编辑了代码。
final=(counter2)/(样本大小)
缩进不正确。如果不使用变量'final',其目的是什么。您在哪里定义和初始化expect
?@yoonghm它应该是'final'(存储1出现前所用转鼓数总和的变量)请您解释一下您的final=(计数器2)/(样本大小)
的逻辑是什么?
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
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
Enter amount of rolls: 500
406
0.812