user1816467
user1816467

Reputation:

Why am I getting a NameError?

I have the following code:

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

And when I go to run it i get the following traceback error:

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

And can not figure out why it is happening.

Someone please shed some light, thanks in advance

Upvotes: 9

Views: 18632

Answers (3)

Urvashi Gupta
Urvashi Gupta

Reputation: 444

import itertools

from itertools import izip_longest

This helped me use itertools and then be able to use izip_longest for iterating through uneven length of arrays.

Upvotes: 2

mgilson
mgilson

Reputation: 309841

It doesn't look like you imported itertools...

from itertools import product

doesn't count as that will only pull product directly into your module's namespace (your module still doesn't know anything about the rest of itertools. Just add:

import itertools

at the top of your script and that error should go away because now you've pulled the itertools namespace into your module's namespace under the name itertools. In other words, to have access to the chain function, you'd use itertools.chain (as you have in your script above).

Upvotes: 17

MRAB
MRAB

Reputation: 20644

You want either:

from itertools import chain, product

and use chain and product, or:

import itertools

and use itertools.chain and itertools.product.

Upvotes: 4

Related Questions