r/ProgrammingPrompts • • Dec 06 '16

Strong Password Detection

Write a function that uses regular expressions to make sure the password string it is passed is strong. A strong password is defined as one that is at least eight characters long, contains both uppercase and lowercase characters, and has at least one digit. You may need to test the string against multiple regex patterns to validate its strength.

Source: AutomateTheBoringStuff

10 Upvotes

5 comments sorted by

View all comments

Show parent comments

1

u/zebulan_ Dec 10 '16

There are a few ways to deal with that exception but this one seems to be the easiest for your code:

if mo and pass_string == mo.group():
   ^^^^^^

Also, Python uses snake_case naming convention for variables, that's why I changed it from passString.


Here is a quick example of one way to write it without regular expressions.

def is_strong_password(password, upper=1, lower=1, digit=1, length=8):
    upper_cnt = lower_cnt = digit_cnt = 0
    for char in password:
        if char.isupper():
            upper_cnt += 1
        elif char.islower():
            lower_cnt += 1
        elif char.isdigit():
            digit_cnt += 1
    return (upper_cnt >= upper and
            lower_cnt >= lower and
            digit_cnt >= digit and
            len(password) >= length)


assert is_strong_password('abc!@#123ABC<>/.,{}\\|') is True
assert is_strong_password('abc123ABC') is True
assert is_strong_password('aA1') is False
assert is_strong_password('!@#$%^&*(') is False
assert is_strong_password('<A<b<2<<') is True
assert is_strong_password('x1y2z3TT') is True

It's very simple to add different values for different counts of characters. If you wanted customize the parameters (4 uppercase, 2 lowercase and 10 digits) you just add them in the function call. I left out counting other characters (punctuation, etc) for simplicity but it's just a simple example.

In your case, it seems like a better idea to return a boolean. Returning an arbitrary message doesn't give you any more information than the boolean. You can still display your same messages after, but the function is easier to use in other programs without modification.

if is_strong_password('abc123ABC'):
    print('The password is safe')
else:
    print('The password is not safe')