初学者,这种题目看也看不明白,有人能告诉我一下吗

img

就是让你生成8个字符长度的字符串当作密码,要求字符串为大小写字母或阿拉伯数字或下划线组成,且连续ASCII不能相邻或相同,也就是说ab,cd...或12,34这种不能连续出现。
可以完全随机再检测是否符合要求,不符合就重新生成。

按照示例,应该是随机生成1个,然后继续生成第二个,同时检这两个是否相邻。如果相邻就退出重新开始。

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))