Reputation: 131
Looking to prove a sibling wrong about how long it can take a computer to guess a specific string by using Brute Force even with the correct number of characters put in. I can get the code to run but I cannot figure out how to get it to print a new string every time it runs. I'm sure I'm over looking something simple. Below are a couple examples of the code I've tried.
import string
import random
random=''.join([random.choice(string.ascii_letters+string.digits) for n in xrange(5)])
while True:
if random != "Steve":
print(random)
if random == "Steve":
print("Found")
This will continually print the same string over and over. I've also tried this without the while
statement just the if
and it doesn't seem to work.
I know enough that once random
picks those 5 randoms characters it won't change until something makes it change but like I said I'm not sure how to do that. I've tried moving random
to different places but doesn't work I just get different error messages.
Can someone help me out.
Upvotes: 1
Views: 666
Reputation: 13498
random=''.join([random.choice(string.ascii_letters+string.digits) for n in xrange(5)])
This doesn't create a new random string each time. At this point random is just a randomly generated string that doesn't change while your while loop runs. Referencing random doesn't create a new string, but rather just gets the first string your generated, since random is just a string in your memory not a function.
Move the random string creation into a function:
import string
from random import choice
def make_random():
return ''.join([choice(string.ascii_letters+string.digits) for n in xrange(5)])
Then run the loop:
while True:
random = make_random()
if random != "Steve":
print(random)
if random == "Steve":
print("Found")
EDIT:
Switched import random
to from random import choice
because random (the variable) was overwriting random (the library) and throwing an attribute error when you try to call random.choice
.
Upvotes: 4
Reputation: 7980
You have two problems here. As @Primusa pointed out, your random generation should be moved inside your loop otherwise it'll only run once. However, your other problem is that you're importing random
and you're also setting a variable to random
. This is where your NameError
is coming from. You've defined random
to be a string, which works on the first iteration of your loop. However, on the second iteration, random
won't have a function called choice
declared for it because it's a string at that point. Rename your random
variable or import the random
package under an alias, like this:
import random as rnd
Upvotes: 2