サイコロを振る
無限ジェネレーターを作りましょう!あなたのタスクは、ジェネレーター simulate_dice_throws() を定義することです。これは 6 面サイコロの結果を、辞書 out の形で生成します。各キーは取りうる出目(1, 2, 3, 4, 5, 6)です。各値はリストで、先頭の値がその出目が出た回数、2 番目の値が全試行回数 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) は 1 または 2 を返します)。
この演習はコースの一部です
Pythonでコーディング面接問題を練習する
演習の手順
- 1 回分のサイコロをシミュレーションして新しい出目を得ます。
- 回数と比率を更新します。
- 更新した辞書を
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(____(____)))