知恵袋で見つけたサイコロの確率の問題をPythonで解いてみました。(^_^;
1個のさいころを3回投げる。1回目に出る目をa1、2回目に出る目をa2、3回目に出る目をa3とし、整数nをn=(a1-a2)(a2-a3)(a3-a1)と定める。このとき、|n|=30である確率を求めよ。
● ProbOfDice1.py
# coding: UTF-8 # ProbOfDice1.py from fractions import Fraction from time import time def main(): pass # Start of Main tm=time() # Timer Start total = count = 0 for a1 in range(1,7): for a2 in range(1,7): for a3 in range(1,7): total+=1 n = (a1-a2)*(a2-a3)*(a3-a1) if abs(n) == 30: count+=1 print("%d/%d = %s"%(count,total,Fraction(count,total))) tm=time()-tm # Timer Stop print("Runtime : %.3f [sec]"%tm) # End of Main if __name__ == '__main__': main()
●実行結果
12/216 = 1/18 Runtime : 0.001 [sec]
P.S.
ちなみに、あまりネストを深くしたくない場合はこちらをどうぞ。(^_^;
● ProbOfDice2.py
# coding: UTF-8 # ProbOfDice2.py from fractions import Fraction from itertools import * total = count = 0 for a in product(range(1,7),repeat=3): a1,a2,a3 = a total+=1 n = (a1-a2)*(a2-a3)*(a3-a1) if abs(n) == 30: count+=1 print("%d/%d = %s"%(count,total,Fraction(count,total)))
- 作者: 辻真吾
- 出版社/メーカー: 技術評論社
- 発売日: 2010/04/24
- メディア: 大型本
- 購入: 19人 クリック: 199回
- この商品を含むブログ (59件) を見る
パーフェクトPython (PERFECT SERIES 5)
- 作者: Pythonサポーターズ,露木誠,ルイス・イアン,石本敦夫,小田切篤,保坂翔馬,大谷弘喜
- 出版社/メーカー: 技術評論社
- 発売日: 2013/03/05
- メディア: 大型本
- 購入: 1人 クリック: 65回
- この商品を含むブログ (30件) を見る