【问题标题】:Python: Roll a dice for 12 times, calculate the probability if each number equally shows up twicePython:掷骰子 12 次,计算每个数字出现两次的概率
【发布时间】:2020-03-02 05:07:33
【问题描述】:

我为标题问题起草了以下代码,但返回结果始终为 0。谁能帮我弄清楚这里有什么问题?

非常感谢!

import random
dice_sides = 6
frequency_list = []
def roll_dice(times):
    results = []
    for roll_num in range(times):
        result = random.randint(1,dice_sides)
        results.append(result)
    for i in range(dice_sides):
        if results.count(i) != 2:
            frequency = 0
            break
        else:
            frequency = 1
    return frequency
def occurrence(N,times):
    for j in range(N):
        frequency_list.append(roll_dice(times))
    prob = frequency_list.count(1)
    return prob

print(occurrence(10000,12))

【问题讨论】:

  • 尝试使用例如调试大量的打印函数来遵循程序的逻辑流程。
  • results.count(i) 返回滚动列表中i 的出现次数。在 10,000 次滚动中,其中一方仅出现 2 次的可能性很小,但极不可能。因此,results.count(i) 在第一个 i 中很可能不是 2,而您在那一刻停止。这需要重新考虑您的算法。

标签: python-3.x probability dice


【解决方案1】:

你可以试试这样的

代码

import random
from collections import Counter



def roll_dice(n_sides, times):
    if n_sides % times:
        return 0

    results = []
    for roll_num in range(times):
        result = random.randint(1, n_sides)
        results.append(result)

    # I'm using set here and will check its length,
    # Counter(results) returns a dict of items (item, count)
    # and if every item has the same count it should have length 1. 
    # More generic statement not only for (2 in this case)
    res_dict = set(Counter(results).values())

    if len(res_dict) == 1:
        return 1
    return 0


def mean(ar):
    return sum(ar)/len(ar)


def occurrence(N, n_sides, times):
    frequency_list = []
    for j in range(N):
        frequency_list.append(roll_dice(n_sides, times))
    prob = mean(frequency_list)
    return prob


if __name__ == '__main__':
    N = 100000 # I intentionally made it 100k 
    n_sides = 6
    times = 12

    res_prob = occurrence(N, times)
    print(res_prob)

输出

0.00604
[Finished in 3.6s]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    相关资源
    最近更新 更多