lundi 3 août 2020

Generating random strings until a given string is generated

This is a program to generate some random string until the 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
iteration = 0
  
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] 
              
    iteration += 1
    attemptThis = attemptNext 
  
print("Target matched after " +
      str(iteration) + " iterations") 



Aucun commentaire:

Enregistrer un commentaire