同じものを含む順列の問題をPythonで解いてみた。(3)

 知恵袋の同じものを含む順列の問題Pythonで解いてみました。(^_^;

 YOKOHAMAの8文字1列に並べるとき、次のような並べ方は何通りあるか。
(1)全ての並び方
(2)OとAが必ず偶数番目にある並べ方
(3)2つのAが隣り合う並べ方
(4)2つのOが隣り合わない並べ方
(5)Y、K、H、Mがこの順にある並べ方

 (2)番が一番、難しかったです。「OとAが必ず偶数番目にある」ということは、「Y、K、H、Mがすべて偶数番目にない」ということですよね。(^_^;

● PermSame3.py

# coding: UTF-8
# PermSame3.py

import itertools
from time import time

def toStr(li,sp=',',fm='%s'):
    return fm%sp.join(li)

def main():
    tm = time() # Timer Start
    P = 'YOKOHAMA'
    setPerms = set(itertools.permutations(P))   # 同じものを含む順列
    cnt1 = cnt2 = cnt3 = cnt4 = cnt5 = 0
    for p in setPerms:
        cnt1+=1
        s = toStr(p,'')
        y,k,h,m = s.index('Y'),s.index('K'),s.index('H'),s.index('M')
        t = [(x+1)%2 for x in (y,k,h,m)]    # 偶奇表
        if  0   not in t: cnt2+=1
        if 'AA'     in s: cnt3+=1
        if 'OO' not in s: cnt4+=1
        if y< k< h< m:    cnt5+=1

    print('(1) %d'%cnt1)
    print('(2) %d'%cnt2)
    print('(3) %d'%cnt3)
    print('(4) %d'%cnt4)
    print('(5) %d'%cnt5)
    print("Runtime : %.3f [sec]"%(time()-tm))   # Timer Stop & Disp

if __name__ == '__main__':
    main()

●実行結果

(1) 10080
(2) 144
(3) 2520
(4) 7560
(5) 420
Runtime : 0.085 [sec]

※参考URL
同じものを含む順列の問題をPythonで解いてみた。(2) - rscのブログ