2012-11-24 62 views
5

は、私は次のコードを持っている:なぜNameErrorが発生しますか?

from crypt import crypt 
from itertools import product 
from string import ascii_letters, digits 

def decrypt(all_hashes, salt, charset=ascii_letters + digits + "-"): 
    products = (product(charset, repeat=r) for r in range(8)) 
    chain = itertools.chain.from_iterable(products) 
    for candidate in chain: 
     hash = crypt(candidate, salt) 
     if hash in all_hashes: 
       yield candidate, hash 
       all_hashes.remove(hash) 
       if not all_hashes: 
       return 

all_hashes = ['aaRrt6qwqR7xk', 'aaacT.VSMxhms' , 'aaWIa93yJI9kU', 
'aakf8kFpfzD5E', 'aaMOPiDnXYTPE', 'aaz71s8a0SSbU', 'aa6SXFxZJrI7E' 
'aa9hi/efJu5P.', 'aaBWpr07X4LDE', 'aaqwyFUsGMNrQ', 'aa.lUgfbPGANY' 
'aaHgyDUxJGPl6', 'aaTuBoxlxtjeg', 'aaluQSsvEIrDs', 'aajuaeRAx9C9g' 
'aat0FraNnWA4g', 'aaya6nAGIGcYo', 'aaya6nAGIGcYo', 'aawmOHEectP/g' 
'aazpGZ/jXGDhw', 'aadc1hd1Uxlz.', 'aabx55R4tiWwQ', 'aaOhLry1KgN3.' 
'aaGO0MNkEn0JA', 'aaGxcBxfr5rgM', 'aa2voaxqfsKQA', 'aahdDVXRTugPc' 
'aaaLf47tEydKM', 'aawZuilJMRO.w', 'aayxG5tSZJJHc', 'aaPXxZDcwBKgo' 
'aaZroUk7y0Nao', 'aaZo046pM1vmY', 'aa5Be/kKhzh.o', 'aa0lJMaclo592' 
'aaY5SpAiLEJj6', 'aa..CW12pQtCE', 'aamVYXdd9MlOI', 'aajCM.48K40M.' 
'aa1iXl.B1Zjb2', 'aapG.//419wZU'] 


all_hashes = set(all_hashes) 
salt = 'aa' 
for candidate, hash in decrypt(all_hashes, salt): 
    print 'Found', hash, '! The original string was', candidate 

をそして、私はそれを実行するために行くとき、私は、次のトレースバックのエラーを取得:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 3, in decrypt 
NameError: global name 'itertools' is not defined 

をそして、それが起こっている理由を把握することはできません。

誰かそれは、あなたのモジュールのに直接productを引っ張ってくるよう

from itertools import product 

はカウントされません...あなたがitertools輸入のようなおかげで、事前

+0

投稿したコードにインデントエラーがあると思います。 (輸入は、そうでなければインデントされています) – mgilson

答えて

13

にそれは見ていない、いくつかの光を当てるしてください名前空間(あなたのモジュールはまだitertoolsの残りの部分については何も知らないだけ追加します。

import itertools 

の上部にあなたのスクリプトとそのエラーはなくなるはずです。itertoolsという名前空間を、モジュールの名前空間に名前itertoolsで引っ張ったからです。つまり、chain関数にアクセスするには、itertools.chainを使用します(上のスクリプトのとおり)。

+0

同じことだが「製品」については –

+0

と言っています。トップには、「import itertools」と「itertools import product'」の両方があります。しかし、あなたはおそらく1または他を使用したいと思うでしょう。この場合、 'itertools'をimportするだけなら' product'を 'itertools.product'に変更します。 – mgilson

1

次のいずれかの希望:

from itertools import chain, product 

chainproduct、または使用します。

import itertools 

itertools.chainitertools.productを使用します。

0
import itertools 

from itertools import izip_longest 

これは私がitertoolsを使用して、配列の不均一な長さを反復処理するためにizip_longestを使用することができるよう助けました。

関連する問題