Как перечислить строку, используя только циклы или рекурсию? (Для примера взлома пароля) - PullRequest
0 голосов
/ 23 октября 2019

Я знаю, что здесь уже есть некоторые ответы. Но посмотри мой код, что я хочу сделать.

genpass = ''

#This is the password that we want to crack.

psd = 'feed'

#This is characters set that is minimised to speed up the problem

characters = {'a','b','c','d','e','f','g','h'}

def brute_force(psd, chr, genpass):
    # this function generates password
    # and check if this is match to psd or not.
   if genpass == psd:
       print('password found!', genpass)

1 Ответ

0 голосов
/ 24 октября 2019

Если вы не можете использовать встроенные функции комбиторинга, рекурсия - путь.

Эта статья Python Guru - отличное место для начала понимания странностей рекурсии

Для этого конкретного примера давайте создадим функцию, которая просто беспокоится об изменении одного индексанашего пароля

def rotate_char(guess, i):
    for c in characters:
        guess[i] = c

Итак, эта функция будет перебирать все символы в одном индексе.

Теперь мы можем вызвать его снова со следующим индексом, рекурсивно изменить все значения.

def rotate_char_recursive(guess, i):
    global answer
    for c in characters:
        guess[i] = c
        rotate_char_recursive(guess, i+1) # call again with next index

Однако, если мы запустим это, мы получим ошибку, так как я получаю слишком большое значение! Нам нужно завершающее условие.

def rotate_char_recursive(guess, i):
    global answer
    for c in characters:
        guess[i] = c
        if "".join(guess) == psd:  # Our check to end recursion
            answer = guess
            return
        if i < len(guess) -1:
            rotate_char(guess, i+1)  # call again with next index
            if len(answer) > 0:  # In case we find the result
                return answer

Теперь, чтобы вызвать нашу рекурсивную функцию:

psd = 'feed'
characters = {'a','b','c','d','e','f','g','h'}
guess = ['a']
answer = []

#Recerusive character rotation
def rotate_char_recursive(guess, i):
    global answer
    for c in characters:
        guess[i] = c
        if "".join(guess) == psd:  # Our check to end recursion
            answer = guess
            return
        if i < len(guess) -1:
            rotate_char_recursive(guess, i+1)  # call again with next index
            if len(answer) > 0:  # In case we find the result
                return answer


while len(guess) < 20:  # Safety catch, in case we do not find the password
    result = rotate_char_recursive(guess, 0)
    if result:
        break
    guess += 'a'  # if password is not found, try a longer password

print(result) # ['f', 'e', 'e', 'd']
...