知恵袋で見つけたサイコロの確率の問題をPythonで解いてみた。

 知恵袋で見つけたサイコロの確率の問題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)))

Pythonスタートブック

Pythonスタートブック

パーフェクトPython (PERFECT SERIES 5)

パーフェクトPython (PERFECT SERIES 5)

Python入門[2&3対応]

Python入門[2&3対応]