I am trying to make a program that will generate a list filled with randomly generated characters, then repeatedly randomizing another until both of them match up.
However, when I run the following program, even at the lowest value, it will continuously run, forever.
import random
import string
combo_length = int(input("pick the number of characters(please write in numbers ONLY): "))
combo_characters = string.ascii_letters + string.digits + string.punctuation
combo = []
for x in range(combo_length):
combo.append(random.choice(combo_characters))
print(''.join(combo))
combo2 = []
for x in range(combo_length):
combo2.append(random.choice(combo_characters))
print(''.join(combo2))
count = 0
while combo != combo2:
count=count+1
for x in range(combo_length):
combo2.append(random.choice(combo_characters))
print("testing")
print(''.join(combo2))
print("the word was", combo)
print("it took", count, "attempts")
You keep on appending to your second list in your while loop. Simple reset your list during each iteration:
import random
import string
combo_length = 3
combo_characters = string.ascii_letters + string.digits + string.punctuation
combo = []
for x in range(combo_length):
combo.append(random.choice(combo_characters))
print(''.join(combo))
combo2 = []
for x in range(combo_length):
combo2.append(random.choice(combo_characters))
print(''.join(combo2))
count = 0
while combo != combo2:
count=count+1
combo2 = [] # <-- reset list
for x in range(combo_length):
combo2.append(random.choice(combo_characters))
print("the word was", ''.join(combo2))
print("it took", count, "attempts")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.