Reputation: 105
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")
Upvotes: 0
Views: 911
Reputation: 1
import random
import string
possibleCharacters = string.ascii_lowercase + string.digits +
string.ascii_uppercase + ' ., !?;:'
a='zero'
c=1
while a != random:
b = ''.join(random.choice(possibleCharacters)for i in range(len(a)))
c=c+1
print(b)
if b ==a:
print(a)
print("target is matched after",c," attermpts")
break
#try this short and simple
Upvotes: 0
Reputation: 1
import string
import random
s1 = input("enter the string:")
n = len(a)
s2 = None
char = string.digits+string.ascii_uppercase+string.ascii_lowercase
c = 1
while s1!=s2:
s2= ''.join(random.choice(char) for i in range(n))
c+=1
print(c,s2)
Upvotes: 0
Reputation: 139
The for
loop is building up a string for attemptNext
. If a character in attemptThis
is equal to its corresponding character in t
, then that character is added to the end of attemptNext
.
The code is weirdly written. In code, it's good practice to avoid not
or !=
in a simple expression in an if-else
statement. In this case, it used !=
. It's often better to use the opposite (==
) and switch the bodies of each.
Upvotes: 1