1. 题目要求
密码要求: 1.长度超过8位 2.包括大小写字母.数字.其它符号,以上四种至少三种 3.不能有相同长度大于2的子串重复 输入描述: 一组或多组长度超过2的字符串。每组占一行 输出描述: 如果符合要求输出:OK,否则输出NG 示例1
>输入:
021Abc9000
021Abc9Abc1
021ABC9000
021$bc9000
>输出:
OK
NG
NG
OK
2. 考点
- 正则的书写 判断字符串中是否存在小写字母 大写字母 数字 符号等。
- 正则的书写 判断字符串中是否存在3个字符的重复
(.{3,}).*\1. - 还可以使用hash记录之前的数据 用于观察后续的数据是否与之前的字符串段相同
3. 核心代码
import re
def test(password: str):
if len(password) <= 8:
return "NG"
count = 0
if re.search('[a-z]', password):
count += 1
if re.search('[A-Z]', password):
count += 1
if re.search('[0-9]', password):
count += 1
if re.search(r'\W', password):
count += 1
if count <= 2:
return "NG"
result = {}
for i in range(len(password) - 2):
if password[i:i + 3] in result:
return "NG"
result[password[i:i + 3]] = 1
return "OK"
if __name__ == '__main__':
while True:
try:
print(test(input("")))
except:
break
4. 代码优化
import re
def test(password: str):
if len(password) <= 8:
return "NG"
flag_1 = re.findall('[a-z]', password)
flag_2 = re.findall('[A-Z]', password)
flag_3 = re.findall('[0-9]', password)
flag_4 = re.findall('\W', password)
if [flag_1, flag_2, flag_3, flag_4].count([]) > 1:
return "NG"
result = re.findall(r'(.{3,}).*\1', password)
if result:
return "NG"
return "OK"
if __name__ == '__main__':
while True:
try:
print(test(input("")))
except:
break