辞書式配列の問題をPythonで解いてみた。

 辞書式配列の問題Pythonで解いてみました。(^_^;
 と、いうより、Javaから翻訳してみました。(^_^;

 ABCDEFの6文字を全て使ってできる順列をABCDEFを1番目として、辞書式に並べる時、次の問いに答えよ。
(1)140番目の文字列を求めよ。
(2)FBCDAEは何番目の文字列か。

 Pythonの順列は、辞書式順序が崩れるので、こういった問題には不向きかと思っていましたが、sortしてから使えばよかったんですね。(^_^;

● DicPerm.py

# coding: UTF-8
# DicPerm.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 = 'ABCDEF'
    sortedPerms = sorted(itertools.permutations(P))     # 辞書式順序
    # //--- (1) ---//
    count = 0
    for p in sortedPerms:
        count+=1
        s1 = toStr(p,'')
        if count==140: break

    # //--- (2) ---//
    count = 0
    for p in sortedPerms:
        count+=1
        s2 = toStr(p,'')
        if s2=='FBCDAE': break

    print('(1) %s'%s1)
    print('(2) %d番目'%count)
    print("Runtime : %.3f [sec]"%(time()-tm))   # Timer Stop & Disp

if __name__ == '__main__':
    main()

●実行結果

(1) BAFCED
(2) 633番目
Runtime : 0.000 [sec]

※参考URL
辞書式配列の問題をJavaで解いてみた。 - rscのブログ
辞書式配列の問題を十進BASICで解いてみた。 - rscのブログ