【问题标题】:Finding Dice Probability找到骰子的概率
【发布时间】:2021-05-22 03:12:00
【问题描述】:

这是我当前的代码:

import random

rolls = 1000  # Set number of rolls here.
num_dice = 2    # Set Number of Dice here.
dice_list = []

for i in range(rolls):
    dice = sum([random.randint(1, 6) for _ in range(num_dice)])
    dice_list.append(dice)

for i in range(num_dice, (num_dice * 6)+1):
    count = dice_list.count(i)
    count = float(count)
    print("Number of {}'s rolled: {} Probability: {}%".format(i,count, round((count / rolls) * 100),2))

我的问题是在计算 i 的百分比时,它会将所有百分比返回为 0%。

更新:当我浏览 StackOverflow 时,我发现它为什么将百分比返回到 0%。要获得实际百分比,您需要将“count”变量作为小数形式。

【问题讨论】:

  • 如果您掷出 126 个 8,您的百分比将是 126/1000,即 0.126 或 12.6%。你关心计算126/(1000 * 100) 这是126/100000,这是错误的。你只是在错误的地方有括号。你可能想要(count / rolls) * 100
  • 您的“更新”完全不正确。将count 作为一个整数变量是完全可以的,并且从 Python 3 开始完全没有必要将它转换为 float
  • P.S. sum 使用生成器就像使用列表一样容易,因此您的括号是多余的:sum(random.randint(1, 6) for _ in range(num_dice))
  • P.P.S.如果您仍在使用 Python 2 版本,则需要在问题中指定。 Python 2.7 变成了officially unsupported as of January 1, 2020,当您提出问题时,我们假设它是不合理的。
  • 嗨@MarkRansom。我使用的平台是 Pycharm CE (Python 2.7)

标签: python for-loop random


【解决方案1】:

试试这个

import random

rolls = 1000  # Set number of rolls here.
num_dice = 2    # Set Number of Dice here.
dice_list = []

for i in range(rolls):
    dice = [random.randint(1, 6) for _ in range(num_dice)]
    x = sum(dice)
    dice_list.append(x)

for i in range(num_dice, (num_dice * 6)+1):
    count = dice_list.count(i)
    print("Number of {}'s rolled: {} Probability: {}%".format(i, count, round(count/rolls*100,2)))

输出

Number of 2's rolled: 37 Probability: 3.7%
Number of 3's rolled: 57 Probability: 5.7%
Number of 4's rolled: 78 Probability: 7.8%
Number of 5's rolled: 114 Probability: 11.4%
Number of 6's rolled: 145 Probability: 14.5%
Number of 7's rolled: 160 Probability: 16.0%
Number of 8's rolled: 129 Probability: 12.9%
Number of 9's rolled: 123 Probability: 12.3%
Number of 10's rolled: 80 Probability: 8.0%
Number of 11's rolled: 50 Probability: 5.0%
Number of 12's rolled: 27 Probability: 2.7%

【讨论】:

  • 除了答案,请解释你做了什么,以便 OP 了解问题出在哪里。
  • 嗨@Ank,我已将计算round(count / (rolls * 100)),2 更新为round(count/rolls*100,2)
  • 我已经更新了我的代码。您需要将“计数”作为十进制形式 (float(count))。
  • @CalebMurnan 你试过你的更新代码了吗?还是不行。
  • @MarkRansom,我已经更新了代码。我需要将计数作为 float(count) 的新变量。
【解决方案2】:

如果我没记错的话,应该是(count / rolls) * 100。这似乎不输出0。但是,我刚从幼儿园毕业,所以不要相信我的话。

import random

rolls = 1000  # Set number of rolls here.
num_dice = 2    # Set Number of Dice here.
dice_list = []

for i in range(rolls):
    dice = [random.randint(1, 6) for _ in range(num_dice)]
    x = sum(dice)
    dice_list.append(x)

for i in range(num_dice, (num_dice * 6)+1):
    count = dice_list.count(i)
    print(f"Number of {i}'s rolled: {count} Probability: {round((count / rolls)*100,2)}")

【讨论】:

    猜你喜欢
    • 2013-07-18
    • 1970-01-01
    • 2015-07-03
    • 2013-12-29
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多