lundi 3 août 2020

Generating random strings until a given string is generated

I can't get the idea of fixing the index in the else part .If the random generated character in the attemptThis[i] doesn't matches with the character in the t[i], we are storing the character in the attemptNext right? And after that when it checks again, only one character is stored in the attemptThis? I don't know whether or not i am asking the right way. I got the idea of statements in the if part. But the else:attemptNext += t[i] is confusing. An exp with example will be greatly appreciated. (code from gfg)

import string
import random

possibleCharacters = string.ascii_lowercase + string.digits + string.ascii_uppercase + ' ., !?;:'

t = "geek"

attemptThis = ''.join(random.choice(possibleCharacters) for i in range(len(t)))
attemptNext = ''

completed = False

while completed == False:
    print(attemptThis)

    attemptNext = ''
    completed = True

    for i in range(len(t)):
        if attemptThis[i] != t[i]:
            completed = False
            attemptNext += random.choice(possibleCharacters)
        else:
            attemptNext += t[i]

    attemptThis = attemptNext

Aucun commentaire:

Enregistrer un commentaire