Home > Mobile >  Creating simple password cracker using numpy arrays
Creating simple password cracker using numpy arrays

Time:11-21

I'm Trying to create a (number) password cracker function using numpy arrays instead of for-loops.

What can I add to my cracker function to avoid this error? (See image of code attached)

Image of my code

I want the cracker function to return the value in the 'possible' array that returns 'Correct' when used as the argument in the password function.

CodePudding user response:

You can refer to my way

def password(correctedpassword):
    if 13 in correctedpassword:
        return "Correct"
    else:
        return "Incorrect"
    
def cracker(testrange):
    possible = np.linspace(0,testrange,testrange 1)
    return password(possible)

Output when call function cracker(100):

'Correct'

Output when call function cracker(12):

'Incorrect'

CodePudding user response:

Please do not post pictures of your code, for future reference. Paste and format it so that another user can copy it and help you easily.


What you need is to apply the function password() on every element of the array possible, and to return the index where the value is correct. The simplest way would be to do it with a loop:

def cracker(testrange):
    possible = np.linspace(0, testrange, testrange   1, dtype=int)
    results = [p for p in possible if password(p) == "Correct"]
    if len(results):
        return results[0]

Alternatively, you can also use numpy's vectorize function:

def cracker(testrange):
    possible = np.linspace(0, testrange, testrange   1, dtype=int)
    results = possible[np.vectorize(password)(possible) == "Correct"]
    if len(results):
        return results[0]

Explanation

Simply put, the function you had, password, takes a single number, checks it, and returns a single output. But you need to do this not for just a single number, but a whole array of numbers (possible). np.vectorize helps you do exactly this; it is no different from a for loop. I will further break down the steps in results = possible[np.vectorize(password)(possible) == "Correct"]:

check_passwords = np.vectorize(password)
# check_passwords is now a new function which will work on an array.
# Basically it is like running the old function password() multiple
# times inside a loop

output = check_passwords(possible)
# array containing ['Incorrect', 'Incorrect', ... , 'Correct', ... , 'Incorrect']

position = output == 'Correct'
# array containing [False, False, ... , True, ... , False]

result = possible[output]
# gives the elements of possible which was 'Correct'

return result[0]
  • Related