質問の持ち歌の確率の問題をPythonで解いてみた。

 質問の持ち歌の確率の問題をPythonで解いてみました。(^_^;
 特定の一曲を'a'として'a'が'a'〜'r'までの18曲の中から選んだ6曲に入っているかどうか、3回目まで全部総当たりで調べてみようとしましたが、totalを18564^3=6397564590144回カウントしないといけないようなので、時間的にちょっと無理なようです。(^_^;
 そこで、数学的に考えると、独立事象になっているようなので、1回目だけ総当たりで調べて 3乗すればいいようです。また、2回目までは総当たりでいけそうなので、確認のため 2回目の結果が 1回目の結果の 2乗になっているかも調べてみました。(^_^;
 場合の数・確率の問題は、検算が難しいため、答えに確信が持てないことが多いですね。(^_^;

● SingLive1.py

# coding: UTF-8
# SingLive1.py

def main():
    from time import time
    from fractions import Fraction
    import itertools

    #    123456789012345678
    C = 'abcdefghijklmnopqr'
    tm = time()  # Timer Start
    total = count1 = count2 = 0
    for c1 in itertools.combinations(C,6):
        total += 1
        if not('a' in c1): count1+=1
        if 'a' in c1:      count2+=1

    print(u"1 回目")
    print("%d / %d = %s"%(count1, total,Fraction(count1, total)))
    print("%d / %d = %s"%(count2, total,Fraction(count2, total)))

    tm = time()-tm  # Timer Stop
    print("Runtime : %.3f [sec]"%tm)

    print(u"∴3 回目")
    print("%s^3 = %s"%(Fraction(count1, total),Fraction(count1, total)**3))
    print("%s^3 = %s"%(Fraction(count2, total),Fraction(count2, total)**3))

    tm = time()  # Timer Start
    total = count1 = count2 = 0
    for c1 in itertools.combinations(C,6):
        for c2 in itertools.combinations(C,6):
            total += 1
            if not('a' in c1) and not('a' in c2): count1+=1
            if 'a' in c1 and 'a' in c2:           count2+=1
    print(u"2 回目")
    print("%d / %d = %s"%(count1, total,Fraction(count1, total)))
    print("%d / %d = %s"%(count2, total,Fraction(count2, total)))

    tm = time()-tm  # Timer Stop
    print("Runtime : %.3f [sec]"%tm)

if __name__ == '__main__':
    main()

● 実行結果

1 回目
12376 / 18564 = 2/3
6188 / 18564 = 1/3
Runtime : 0.016 [sec]
∴3 回目
(2/3)^3 = 8/27
(1/3)^3 = 1/27
2 回目
153165376 / 344622096 = 4/9
38291344 / 344622096 = 1/9
Runtime : 232.066 [sec]

初めてのPython 第3版

初めてのPython 第3版