cap_letters = [“A”,“B”,“C”,“D”,“E”]
小字母= [“a”,“b”,“c”,“d”,“e”]
符号 = ["@", "$", "&"]
数字 = ["1", "2", "3", "4", "5"]
可以使用什么算法来生成遵循以下策略的密码。
(应该很快,超级快)
• 它必须包含每个类别中至少一个元素;
• 必须以字母(大写或小写)开头;
• 不得包含超过两个大写字母;
• 不得包含两个以上的特殊符号。
解决方案应该是一个Python程序,它以给定的数字作为密码长度,并打印给定长度的所有有效密码(包括索引)。例如,如果给定长度为4,程序可能会返回以下结果:
1 Aa1$ 2巴1$ 3 Ca1$ ...
如果您愿意,可以对这些集合(字母、数字和特殊符号)进行硬编码或读入,但应从控制台读入给定长度以便于测试
我尝试使用 itertools.product 来查找创建给定字母、数字和特殊符号的不同组合,但密码长度超过 5 时,代码将永远无法运行
import itertools
def generate_valid_passwords(length):
capital_letters = ['A', 'B', 'C', 'D', 'E'] lowercase_letters = ['a', 'b', 'c', 'd', 'e']
digits = ['1', '2', '3', '4', '5']
special_symbols = ['$', '&', '%']
valid_passwords = []
index = 1
#Generate all possible combinations of elements combinations = itertools.product(capital_letters + lowercase_letters + digits + special_symbols, repeat=length)
for combination in combinations:
#check if the combination satisfies the rules
if any(char in capital_letters for char in combination) \ and any(char in lowercase_letters for char in combination) \ and any(char in digits for char in combination) \ and any(char in special_symbols for char in combination) \ and combination[0].isupper() \ and sum(1 for char in combination if char.isupper()) < 2 \ and sum(1 for char in combination if char in special_symbols) < 2:
password = ''.join(combination) valid_passwords.append((index, password)) index += 1 return valid_passwords def main(): length = int(input("Enter the length of the passwords: ")) valid_passwords = generate_valid_passwords(length) if valid_passwords: print("Valid passwords of length {}:".format(length)) for index, password in valid_passwords: print("{} {}".format(index, password)) else: print("No valid passwords of length {} found.".format(length)) if __name__ == "__main__": main()
使用多重处理: https://www.geeksforgeeks.org/multiprocessing-python-set-1/
运行多个实例。它可能会消耗CPU资源...