Skip to content

Instantly share code, notes, and snippets.

@skilldeliver
Created June 25, 2019 10:06
Show Gist options
  • Save skilldeliver/96ac15a24e0a31c54fd6ced3c10fc4cb to your computer and use it in GitHub Desktop.
Save skilldeliver/96ac15a24e0a31c54fd6ced3c10fc4cb to your computer and use it in GitHub Desktop.
Code Jam 5 Qualifier
import random
import string
def generate_password(
password_length: int = 8,
has_symbols: bool = False,
has_uppercase: bool = False,
ignored_chars: list = None,
allowed_chars: list = None
) -> str:
"""Generates a random password.
The password will be exactly `password_length` characters.
If `has_symbols` is True, the password will contain at least one symbol, such as #, !, or @.
If `has_uppercase` is True, the password will contain at least one upper case letter.
If `ignored_chars` is passed, characters from the list won't be used.
If `allowed_chars` is passed, only characters from the list will be used.
Only one of the optional char list can be passed.
"""
password = str()
if ignored_chars and allowed_chars:
# both lists to be passed at the same time
raise UserWarning("You can't pass both char lists. Only one of them.")
elif allowed_chars:
# generate password using only `allowed_chars` symbols
password = "".join([random.choice(allowed_chars) for _ in range(password_length)])
else:
# new list for the characters
chars = list()
# different lists for different categories of characters
symbols = list(string.punctuation)
uppercases = list(string.ascii_uppercase)
other = list(string.ascii_lowercase + string.digits)
if ignored_chars:
# remove all ignonered characters from the list
for c in ignored_chars:
if c in symbols:
symbols.remove(c)
elif c in uppercases:
uppercases.remove(c)
else:
other.remove(c)
if has_symbols:
# generates random portion of symbols
rand_int = random.randint(1, password_length-1)
chars += random.choices(population=symbols, k=rand_int)
if has_uppercase:
# generates random portion of uppercase letters
rand_int = random.randint(1, password_length - len(chars))
chars += random.choices(population=uppercases, k=rand_int)
if len(chars) != password_length:
# if there are places left they must be filled with other symbols
left = password_length-len(chars)
chars += random.choices(population=other, k=left)
# at the end shuffle the characters and contruct the string
random.shuffle(chars)
password = ''.join(chars)
return password
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment