14

次のコードは、文字列のすべての順列を生成します。

def permutations(word):
    if len(word)<=1:
        return [word]

    #get all permutations of length N-1
    perms=permutations(word[1:])
    char=word[0]
    result=[]
    #iterate over all permutations of length N-1
    for perm in perms:
        #insert the character into every possible location
        for i in range(len(perm)+1):
            result.append(perm[:i] + char + perm[i:])
    return result

それがどのように機能するか説明できますか?再帰がわかりません。

4

2 に答える 2

55

アルゴリズムは次のとおりです。

  • 最初の文字を削除
  • 残りの文字のすべての順列を見つける (再帰的ステップ)
  • 可能なすべての場所で削除された手紙を再挿入します。

再帰の基本ケースは 1 文字です。1 つの文字を並べ替える方法は 1 つしかありません。

実施例

開始単語が であると想像してくださいbar

  • まず、 を取り外しますb
  • の順列を求めarます。これによりarとが得られraます。
  • これらの単語のそれぞれについてb、すべての場所 に入れます。
    • ar-> barabrarb
    • ra-> brarbarab
于 2012-12-23T04:11:32.960 に答える
7

長さ 2 の文字列と長さ 3 の文字列の手順を下に書きました。

順列('ab')

len('ab') is not <= 1 
perms = permutations of 'b'
len('b') <= 1 so return 'b' in a list
perms = ['b']
char = 'a'
result = []
for 'b' in ['b']:
    for 0 in [0,1]:
        result.append('' + 'a' + 'b')
    for 1 in [0,1]:
        result.append('b' + 'a' + '')
result = ['ab', 'ba'] 

順列('abc')

len('abc') is not <= 1
perms = permutations('bc')
perms = ['bc','cb']
char = 'a'
result =[]
for 'bc' in ['bc','cb']:
    for 0 in [0,1,2]:
        result.append('' + 'a' + 'bc')
    for 1 in [0,1,2]:
        result.append('b' + 'a' + 'c')
    for 2 in [0,1,2]:
        result.append('bc' + 'a' + '') 
for 'cb' in ['bc','cb']:
    for 0 in [0,1,2]:
        result.append('' + 'a' + 'cb')   
    for 1 in [0,1,2]:
        result.append('c' + 'a' + 'b')   
    for 2 in [0,1,2]:
        result.append('cb' + 'a' + '')
result = ['abc', 'bac', 'bca', 'acb', 'cab', 'cba']  
于 2014-07-22T05:30:19.147 に答える