I coded a python solution for the question below. I am after the fastest solution. Also, I would be grateful if you could point out parts that are not pythonic / inefficient.
Question: A website requires the users to input username and password to register. Write a program to check the validity of password input by users. Following are the criteria for checking the password:
- At least 1 letter between [a-z]
- At least 1 number between [0-9]
- At least 1 letter between [A-Z]
- At least 1 character from [$#@]
- Minimum length of transaction password: 6
import warnings
password = 'P@ss1234'
def check_number(s):
''' Check whether the input string is a digit. '''
try:
int(s)
return True
except:
# do not catch error
return False
def check_validity(pw):
''' Return True if input pw is valid, and return False if invalid.'''
special_chars = ['$','#','@']
if isinstance(pw,str): pw=list(pw) # I could have appointed to a diff var name
else: warnings.warn('Password has to be a string object.')
res = False
valid_dict={'small_let':False, 'num':False, 'special_chars':False,
'cap_let':False, 'len':False } # is using a dict efficient?
if len(pw)>= 6: valid_dict['len']=True
for i in pw:
if i.islower(): valid_dict['small_let'] = True
if i in special_chars: valid_dict['special_chars'] = True
if i.isupper(): valid_dict['cap_let'] = True
if not valid_dict['num']: valid_dict['num'] = check_number(i)
if all(valid_dict.values()): res = True
return res
print check_validity(password)
P.S: I am not interested in a module / package that can do this faster or more securely. There does not actually exist a website or a username, this is a simple coding exercise.
Also, linked to this post.
check_number(s)
you can use built-ins.isdigit()
\$\endgroup\$