Password Validation
Note: This page contains a small but interesting piece of Python code which I call snippets. You can find more such codes on my Python snippets page.
Contents
Problem ¶
You're interviewing to join a security team. They want to see you build a password evaluator for your technical interview to validate the input.
Task:
Write a program that takes in a string as input and evaluates it as a valid password. The password is valid if it has at a minimum 2 numbers, 2 of the following special characters ('!', '@', '#', '$', '%', '&', '*'), and a length of at least 7 characters.
If the password passes the check, output 'Strong', else output 'Weak'.
Input Format:
A string representing the password to evaluate.
Output Format:
A string that says 'Strong' if the input meets the requirements, or 'Weak', if not.
Sample Input:
Hello@$World19
Sample Output:
Strong
Solution ¶
Here is my solution to the above problem. Remember that there could be more than one way to solve a problem. If you have a more efficient or concise solution, please leave a comment.
Using RegEx
import re
if re.match('^(?=.*\d.*\d)(?=.*[!@#$%&*].*[!@#$%&*]).{7,}$', input()):
print("Strong")
else:
print("Weak")
Using the conventional method
pw=input()
special_chars=('!', '@', '#', '$', '%', '&', '*')
nums=[str(x) for x in range(10)]
pw_type='Weak'
num_count=0
spcl_count=0
if len(pw)>=7:
for x in pw:
if num_count<2 or spcl_count<2:
if x in nums:
num_count+=1
if x in special_chars:
spcl_count+=1
else:
break
if num_count>=2 and spcl_count>=2:
pw_type='Strong'
print(pw_type)
Explanation ¶
As we notice, the RegEx code is comparitively concise and easier to use once you get a hang of it. I will explain only the RegEx code as the conventional code is self explanatory.
My approach (or the algorithm)¶
Create a RegEx that
- searches for a number twice.
- searches for these special characters
!@#\$%&*
twice. - checks if the string length is 7 or above.
The code¶
-
^(?=.*\d.*\d)(?=.*[!@#$%&*].*[!@#$%&*]).{7,}$
RegEx pattern-
^
matches the beginning of the string. -
(?=.*\d.*\d)
Positive lookahead (searches for at least 2 numbers preceded by any or no characters)-
.
any character. -
*
any number of repetitions of the above including zero. So.*
matches any or no characters. -
\d
matches a number (0-9).
-
-
(?=.*[!@#$%&*].*[!@#$%&*])
Positive lookahead (searches for at least 2 special characters preceded by any or no characters)-
[!@#$%&*]
Character set of special characters given in the problem statement.
-
-
.{7,}
matches any characters occuring 7 times or more in a sequence. Used for measuring password length. -
$
matches the end of the string.
-
The problem question is picked from SoloLearn. Here is my SoloLearn code and my SoloLearn profile page.
Last updated 2021-01-09 17:33:06.200287 IST
Comments