開始使用免費開始

擲骰子

來建立一個無限產生器吧!你的任務是定義 simulate_dice_throws() 產生器。它會以字典 out 的形式產生 6 面骰每次擲出的結果彙總。每個鍵是可能的結果(123456)。每個值是一個串列:第一個值是該結果出現的次數,第二個值是該次數相對於總擲數 total 的比率。舉例來說(當 total = 4 時):

{
  1: [2, 0.5],
  2: [1, 0.25],
  3: [1, 0.25],
  4: [0, 0.0],
  5: [0, 0.0],
  6: [0, 0.0]
}

提示:使用已匯入的 random 模組中的 randint() 函式。它會在指定區間內產生一個隨機整數(例如 randint(1, 2) 可能是 12)。

本練習屬於課程

Python 程式面試題實作練習

檢視課程

練習說明

  • 模擬一次擲骰,取得一個新數字。
  • 更新該數字的次數與比率。
  • 傳回(yield)更新後的字典。
  • 建立產生器並模擬 1000 次擲骰。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

def simulate_dice_throws():
    total, out = 0, dict([(i, [0, 0]) for i in range(1, 7)])
    while True:
        # Simulate a single toss to get a new number
        num = ____
        total += 1
        # Update the number and the ratio of realizations
        out[num][0] = ____
        for j in range(1, 7):
        	out[j][1] = round(____/____, 2)
        # Yield the updated dictionary
        ____

# Create the generator and simulate 1000 tosses
dice_simulator = ____
for i in range(1, 1001):
    print(str(i) + ': ' + str(____(____)))
編輯並執行程式碼