1 回答

TA貢獻1840條經驗 獲得超5個贊
對代碼進行簡單修改即可獲取滾動值的計數。如果您特別想使用 Numpy,請告訴我。
代碼
from random import randint # only using randint so only import it
import numpy as np # not needed
class Dice:
def roll(self):
return randint(1, 6)
frequencies = [0]*13 # array to hold results of dice roll
# will use frequencies 2 to 12)
dice = Dice()
remaining_rolls = 10000 # number of remaining rolls
while remaining_rolls > 0:
roll = dice.roll() + dice.roll() # roll sum
frequencies[roll] += 1 # increment array at index roll by 1
remaining_rolls -= 1
print(frequencies)
輸出
[0, 0, 272, 583, 829, 1106, 1401, 1617, 1391, 1123, 863, 553, 262]
使用列表理解作為 while 循環的替代方案
frequencies = [0]*13
for roll in [dice.roll() + dice.roll() for _ in range(10000)]:
frequencies[roll] += 1
print(frequencies) # Simpler Output
解釋
任務:
frequencies = [0]*13
創建一個包含 13 個元素的數組,索引從 0 到 12,最初用零填充。
每個骰子的總和是 2 到 12 之間的數字(即 11 個值)
為了增加一卷的計數,我們使用:
frequencies[roll] += 1
這是語法糖:
frequencies[roll] = frequencies[roll] + 1
例如,如果 roll = 5,我們將頻率[5] 加 1,這會增加 roll 為 5 的次數的計數。
兩個 bin 始終為零:
frequencies[0] and frequencies[1]
這是因為 2 <= roll <= 12 所以我們永遠不會增加 bin 0 和 1。
- 1 回答
- 0 關注
- 144 瀏覽
添加回答
舉報