cap_letters = [“A”, “B”, “C”, “D”, “E”]
small_letters = [“a”, “b”, “c”, “d”, “e”]
symbols = [“@”, “$”, “&”]
numbers = [“1”, “2”, “3”, “4”, “5”]
What algorithm can be used to generate a password that follows the policy below.
(It should be fast, super fast)
• it must include at least one element from each category;
• it must start with letters (capital or lower-case);
• it must not include more than two capital letters;
• it must not include more than two special symbols.
The Solution should be a Python program, which takes a given number as the password length, and print all valid passwords (including indices) with the given length. For example, if the given length is 4, the program may return the follow result:
1 Aa1$
2 Ba1$
3 Ca1$ …
These sets (letters, digits, and special symbols) can be hard-coded or read in if you prefer, but the given length should be read in from the console for the easy testing
I tried using itertools.product to find create different combinations of the given letters, digital, and special symbols but beyond 5 password length the code takes forever to run
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()
Elijah Echekwu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.