1

練習用の順列用のジェネレーター関数を書こうとしています。しかし、それは何も返しません。しかし、´´yield new [k]´´を´´lis.append(new [k])´´に置き換えると、正しい順列のリストが得られます。歩留まりに問題がありますか?

tup=(1,2,3) # tup can be any sequence
new=[[]]*(len(tup)+1) # memory; new[0]=[], new[1] will be length 1 permutation, etc.
lis=[]  # the list of permutations

def repeat(k): # recursion
    for i in tup:
        if i in new[k-1]:
            continue # permutation can't repeat
        else: new[k]=new[k-1]+[i]

        if k==len(tup): 
             yield new[k]
        else:
             repeat(k+1)

gen=repeat(1)
for i in gen:
    print(i)
4

2 に答える 2

0

練習用のジェネレーターを使用して、複数の長さの順列を生成するためのアルゴリズムを作成しようとしていると思います。

サイズについては、この質問を試してください: Pythonでリストのすべての順列を生成する方法

python3に変換する必要がありますが、これはそれほど大きな問題ではないはずです。

残念ながら、あなたの問題は、の使用ではなく、アルゴリズムにあると思いますyield。これは私には問題ないようです。

于 2012-06-26T02:33:32.167 に答える
0

これは再帰関数ですが、再帰から値を渡さないため、何も返されません。

呼び出しをに変更する必要があります

repeat(k+1)

for x in repeat(k+1):
    yield x

結果の関数は次のようになります。

tup=(1,2,3) # tup can be any sequence
new=[[]]*(len(tup)+1) # memory; new[0]=[], new[1] will be length 1 permutation, etc.
lis=[]  # the list of permutations

def repeat(k): # recursion
    for i in tup:
        if i in new[k-1]:
            continue # permutation can't repeat
        else: new[k]=new[k-1]+[i]

        if k==len(tup): 
             yield new[k]
        else:
             for x in repeat(k+1):
                 yield x

for i in repeat(1):
    print(i)

どちらが機能しますか。

次のステップは、グローバル変数を取り除くことです。

于 2012-06-26T04:50:53.070 に答える