【发布时间】:2022-01-10 22:38:55
【问题描述】:
我正在学习 100 天的 Python 代码,我正在尝试通过接收用户输入的密码来创建 Python 密码生成器。
p>下面的程序运行并生成所需的输出,但我知道肯定有比在范围内迭代任意次数来生成固定长度密码更好的方法。
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
print("Welcome to the PyPassword Generator!")
nr_letters= int(input('How many letters would you like in your password?: '))
nr_symbols = int(input('How many symbols would you like?: '))
nr_numbers = int(input('How many numbers would you like?: '))
password = ""
# Generate unshuffled password
# for i in range(1, (nr_letters + 1)):
# password += random.choice(letters)
# for i in range(1, (nr_symbols + 1)):
# password += random.choice(numbers)
# for i in range(1, (nr_numbers +1)):
# password += random.choice(symbols)
# print(password)
letter_counter = 0
symbol_counter = 0
number_counter = 0
# NOTE: This seems dumb but it works so...
for i in range(0, 100):
random_int = random.randint(0, 2)
if random_int == 0 and letter_counter < nr_letters:
password += random.choice(letters)
letter_counter += 1
elif random_int == 1 and symbol_counter < nr_symbols:
password += random.choice(symbols)
symbol_counter += 1
elif random_int == 2 and number_counter < nr_numbers:
password += random.choice(numbers)
number_counter += 1
print(password)
有没有一种更简洁的方法可以通过 Python for 循环创建一个随机的、固定长度的字符串?
对于未来,循环遍历的次数多于生成所需输出的次数是否有一个主要缺点?
【问题讨论】:
-
您可能对
chr()函数感兴趣。 -
您的方法的缺点是,它不正确。您的代码将生成不符合用户指定要求的密码。不经常(它可能会通过手动测试),但它会。
-
过度迭代的最大缺点是它可能需要太长时间。第二个是它可能会降低结果的随机性。
-
使用google,您可以从 ~10200 个指向 stackoverflow 上的“密码生成器 python”的链接中进行选择。我认为您可以自己提出不同的想法。
-
为什么不直接生成未洗牌密码然后使用
random.shuffle?
标签: python performance for-loop range shuffle