“编写程序,随机生成10条密码,,并将它们显示出来。
要求:
1,密码的构成:52个大小写英文字母和10个数字(0~9),以及下划线””中的任意一个;
2、密码的长度:8个字符
3、生成的密码,不允许出现连续两个数字或字母是相邻或相同的。即如果生成的密码为"dAlsy5gh"、"RihLaaBU”,则被视为不符合要求,不计入密码条数内。
import string
import random
passwords = []
# 使用的字符串,数字+下划线+字母
s = string.digits + string.ascii_letters + "_"
# 因为数字和字母不能连续,也就是数字的下一位只能是字母或者下划线.
s1 = string.digits + "_" # 不包含字母
s2 = string.ascii_letters + "_" # 不包含数字
s3 = string.digits + string.ascii_letters # 不包含下划线
while len(passwords) < 10:
password = ""
for i in range(8):
if i == 0:
c = random.choice(s) # 先选取一个字符
password += c
else:
last = password[i-1] # 获取上一个字符
if last.isdigit(): # 如果上一个字符是数字,就不能再随机选取数字了
c = random.choice(s2)
elif last == "_":
c = random.choice(s3)
else:
c = random.choice(s1)
password += c
if password not in passwords: # 防止密码重复
passwords.append(password)
print("生成的密码: {}".format(passwords))
结果:
如果觉得答案对你有帮助,请点击下采纳,谢谢~