python - 掷骰子的 Python 程序计算出现 6 之前的掷骰数
问题描述
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
谢谢
解决方案
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
推荐阅读
- python - extracting attribute values of tag in Scrapy
- excel - 根据单元格值将一系列单元格向下复制指定次数
- css - 为什么输入字段会使用 font-style:italic 减小宽度?
- vhdl - 修改 verilog 或 vhdl RTL 文件后,vivado 模块设计器未更新模块设计中的 RTL 接口
- javascript - Awaiting Redux Action w/ React Hooks
- php - 获取名称而不是 ID 一对一关系
- xml - 需要帮助将值从一个对等 XML 组放到另一个 XML 组
- email - 如何为电子邮件配置服务器(ldap?)?
- aws-lambda - 在 VPC 中使用 AWS Lambda 实施 ReCaptcha V3
- html - HTML CSS如何显示具有相同宽度和不同高度的元素