質問の期待値の問題をPythonで解いてみた。

 昨日のJavaプログラムPythonに翻訳してみました。(^_^;
 ちょっと遅いけど、やっぱり、楽だねぇ。

● ExpectedValue1.py

# coding: UTF-8
# ExpectedValue1.py

import itertools
from time import time
from fractions import Fraction

def countRen(c):
    count=1
    for i in range(len(c)-1):
        if c[i]!=c[i+1]:
            count+=1
    return count

def main():
    pass # code goes here
    tm=time()  # Timer Start

    p = list('AAAAABBBBB')
    r = len(p)
    count = [0]*r
    total = 0
    for q in list(set(itertools.permutations(p,r))): # 同じものを含む順列
        total+=1
        count[countRen(q)-1]+=1

    numerator = 0
    for i in range(r):
        print("%2d:%3d"%(i+1,count[i]))
        numerator += (i+1)*count[i]
    print(u"∴ %d / %d = %s"%(numerator,total,Fraction(numerator,total)))

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

if __name__ == '__main__':
    main()

●実行結果

 1:  0
 2:  2
 3:  8
 4: 32
 5: 48
 6: 72
 7: 48
 8: 32
 9:  8
10:  2
∴ 1512 / 252 = 6
Runtime : 1.106 [sec]

Pythonスタートブック

Pythonスタートブック

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

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

初めてのPython 第3版

初めてのPython 第3版