python - itertools 掷骰子 : doubles roll twice

标签 python algorithm python-itertools python-collections

我正在尝试学习 Python 库 itertools,我认为一个好的测试是模拟掷骰子。使用 product 并使用 collections 库计算可能的方法数,很容易生成所有可能的滚动。我正在尝试解决游戏中出现的问题 Monopoly : 当掷 double 时,你再次掷骰,你的最终总数是两次掷骰的总和。

下面是我解决问题的开始尝试:两个计数器,一个用于 double ,另一个用于非 double 。我不确定是否有将它们结合起来的好方法,或者这两个计数器是否是最好的方法。

我正在寻找一种巧妙的方法来解决(通过枚举)使用 itertools 和集合的 double 掷骰子问题。

import numpy as np
from collections import Counter
from itertools import *

die_n = 2
max_num = 6

die = np.arange(1,max_num+1)
C0,C1  = Counter(), Counter()

for roll in product(die,repeat=die_n):
    if len(set(roll)) > 1: C0[sum(roll)] += 1
    else: C1[sum(roll)] += 1

最佳答案

为了简单起见,这里省略了 numpy:

首先,生成所有卷,无论是单卷还是双卷:

from itertools import product
from collections import Counter

def enumerate_rolls(die_n=2, max_num=6):
    for roll in product(range(1, max_num + 1), repeat=die_n):
        if len(set(roll)) != 1:
            yield roll
        else:
            for second_roll in product(range(1, max_num + 1), repeat=die_n):
                yield roll + second_roll

现在进行一些测试:

print(len(list(enumerate_rolls()))) # 36 + 6 * 36 - 6 = 246
A = list(enumerate_rolls(5, 4))
print(len(A)) # 4 ** 5 + 4 * 4 ** 5 - 4 = 5116
print(A[1020:1030]) # some double rolls (of five dice each!) and some single rolls

结果:

246
5116
[(1, 1, 1, 1, 1, 4, 4, 4, 4, 1), (1, 1, 1, 1, 1, 4, 4, 4, 4, 2), (1, 1, 1, 1, 1, 4, 4, 4, 4, 3), (1, 1, 1, 1, 1, 4, 4, 4, 4, 4), (1, 1, 1, 1, 2), (1, 1, 1, 1, 3), (1, 1, 1, 1, 4), (1, 1, 1, 2, 1), (1, 1, 1, 2, 2), (1, 1, 1, 2, 3)]

要获得总数,请使用特殊的 Counter 功能:

def total_counts(die_n=2, max_num=6):
    return Counter(map(sum, enumerate_rolls(die_n, max_num)))

print(total_counts())
print(total_counts(5, 4))

结果:

Counter({11: 18, 13: 18, 14: 18, 15: 18, 12: 17, 16: 17, 9: 16, 10: 16, 17: 16, 18: 14, 8: 13, 7: 12, 19: 12, 20: 9, 6: 8, 5: 6, 21: 6, 22: 4, 4: 3, 3: 2, 23: 2, 24: 1})
Counter({16: 205, 17: 205, 18: 205, 19: 205, 21: 205, 22: 205, 23: 205, 24: 205, 26: 205, 27: 205, 28: 205, 29: 205, 25: 204, 20: 203, 30: 203, 15: 202, 14: 200, 31: 200, 13: 190, 32: 190, 12: 170, 33: 170, 11: 140, 34: 140, 35: 102, 10: 101, 9: 65, 36: 65, 8: 35, 37: 35, 7: 15, 38: 15, 6: 5, 39: 5, 40: 1})

注意:此时,无法计算总数的概率。您必须知道是双卷还是全卷才能正确称重。

关于python - itertools 掷骰子 : doubles roll twice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9643191/

相关文章:

python - 具有 2 个 df 的 Pandas 师

python autopy问题/困惑

python - TensorFlow实验: how to avoid loading all data in memory with input_fn?

python - numpy 数组列表格式

c# - 您知道 Gauss Newton 和 Levenberg Marquardt 方法的 C# 实现吗?

algorithm - 有没有一种简单的方法可以记住红黑树的旋转方法?

python - 使用 itertools 进行格雷码顺序的笛卡尔积?

python - itertools.cycle(iterable) 与 while True

algorithm - 重新审视包装问题

python - 如何将元组列表的字典相互比较?