Search code examples
pythonfor-looppasswords

Python is not checking if the systematically randomized generated password is equal to the given password


Essentially I am trying to create a program that can go through all possible passwords one can create with aaaa-zzzz. I have the code down where it can count the number of passcodes and what they are such as 'abcd' or 'xkyz'. However when I try to implement the checking part of the code to pretty much tell it to stop and that the answer has been found, the program negates it and will go all the way down to 'zzzz' even if the given password is 'aaaa'.

import random
import sys
my_password = "aaaa"
guess_num = 0
done = False
while not done:  #setup for the loop

my_password = "aaaa"
prime = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',]
prime2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',]
prime3 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',]
prime4 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',]
for a in prime:
    for b in prime2:
        for c in prime3:
            for d in prime4:
                first = (a + b + c + d) #loop that goes through  all aaaa-zzzz
                guess = str(first)
                if guess == my_password:
                    print("found it after ", str(guess_num), " tries")
                    done = True
                elif guess != my_password:
                    guess_num = guess_num + 1
                    print(guess, guess_num)           

print(guess)


Solution

  • You should use itertools.product and string.ascii_lowercase to generate your password guesses. Then you can simplify your code to a simple loop:

    import itertools
    import string
    
    guess_num = 1
    my_password ='abcd'
    prime = string.ascii_lowercase     # abc...xyz
    for guess in itertools.product(prime, repeat=4):
        if ''.join(guess) == my_password:
            print(f"found it after {guess_num} tries")
            break
        guess_num += 1