我一直在查看堆栈并花了几个小时浏览来尝试解决这个问题。
任务是:
编写一个名为 dicerolls 的 Python 函数来模拟掷骰子。你的函数应该有两个参数:骰子的数量 k 和掷骰子的次数 n。该函数应模拟随机滚动 k 个骰子 n 次,并跟踪每个总面值。然后它应该返回一个字典,其中包含每个可能的总面值出现的次数。因此,将函数调用为 diceroll(k=2, n=1000) 应返回一个字典,如下所示: {2:19,3:50,4:82,5:112,6:135,7:174,8:133 ,9:114,10:75,11:70,12:36}
到目前为止,我已经成功定义了 dice 函数,但我遇到的困难是将 k(掷骰数)添加到 dicerolls 函数中。到目前为止我所拥有的:
from numpy import random
def dice():
return random.randint(1, 7)
def diceroll(number_of_times):
counter = {n : 0 for n in range(2, 13)}
for i in range(number_of_times):
first_dice = dice()
second_dice = dice()
total = first_dice + second_dice
counter[total] += 1
return counter
diceroll(1000)
输出: {2: 19, 3:49, 4:96, 5:112, 6:150, 7:171, 8:151, 9:90, 10:89, 11:47, 12: 26}
如有任何建议,我们将不胜感激。
回答后编辑代码
import random
def diceroll(k, n, dice_sides=6):
# prepare dictionary with zero values for all possible results
counter = {n : 0 for n in range(k, k*dice_sides + 1)}
# roll all the dice
for i in range(n):
dice_sum = sum(random.choices(range(1, dice_sides + 1), k = k))
counter[dice_sum] += 1
return counter
diceroll(k=2, n=1000)
输出: {2: 20, 3:49, 4:91, 5:116, 6:140, 7:138, 8:173, 9:112, 10:72, 11:65, 12: 24}
最佳答案
您可以使用collectors.counter来跟踪卷。
另外,这可能取决于偏好,但没有理由为像随机这样简单的东西导入 numpy。
In [1]: import random
In [2]: from collections import Counter
In [3]: def dice():
...: return random.randint(1,7)
...:
In [4]: def dice_roll(number_of_times):
...: counter = Counter()
...: for i in range(number_of_times):
...: first_dice = dice()
...: second_dice = dice()
...: total = first_dice + second_dice
...: counter[total] += 1
...: return counter
...:
In [5]: def multiple_rolls(k, number_of_times):
...: final_counter = Counter()
...: for i in range(k):
...: final_counter.update(dice_roll(number_of_times))
...: return final_counter
...:
In [6]: multiple_rolls(2, 1000)
Out[6]:
Counter({9: 247,
5: 170,
10: 198,
6: 196,
8: 251,
4: 123,
12: 102,
7: 249,
14: 44,
2: 44,
11: 184,
3: 105,
13: 87})
关于根据输入参数模拟掷骰子的Python函数 1) 骰子数量 2) 掷骰子数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65071627/