2011-12-31 12 views
2

私は非常にPythonの新機能です(昨日始めたばかりです)、文字セットの順列を作成しようとしています。暗号プログラムで使用するascii_lowercase。私は現在、使用しています次:すべての順序で文字セットのすべての順列を作成する方法 - Python

...function definitions etc 
while i <= num: 
    for k in itertools.combinations_with_replacement(charset, i): 
    nhash = str(''.join(k)) 
    fp.write(nhash + '\n') 
    ...hashing code and other file I/O 
    i += 1 

はそれが与える「ABC」の文字セットが指定:

a 
b 
c 
aa 
ab 
ac 
bb 
...etc 

それは正しく「AA」を打つために管理します。しかし、それは 'ba'と暗号解読アルゴリズムab!= baを見逃していました。基本的にitertools.permutations_with_replacement関数を探したいと思います。

baとbbの両方を取得する方法はありますか?

答えて

2

そのあなたがitertools.productはなくitertools.combinations_with_replacement

必要があるようで、ここであなたはいつでも使用することができ、それを印刷するのではなく、値を使用する必要がある場合itertools.productは

charset='ABC' 
print '\n'.join(''.join(p) for i in xrange(1,len(charset)+1) 
       for p in itertools.product(charset, repeat=i)) 

A 
B 
C 
AA 
AB 
AC 
BA 
BB 
BC 
CA 

注意して実装したものです発電機

for x in (''.join(p) for i in xrange(1,len(charset)+1) 
       for p in itertools.product(charset, repeat=i)): 
    print x 
    ...hashing code and other file I/O 
+0

美しい!信じられないほどクリーンなコード。どうもありがとうございました! – tophersmith116

関連する問題