首页 > 试题广场 >

密码验证合格程序

[编程题]密码验证合格程序
  • 热度指数:404078 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

密码要求:

1.长度超过8位

2.包括大小写字母.数字.其它符号,以上四种至少三种

3.不能有长度大于2的包含公共元素的子串重复 (注:其他符号不含空格或换行)

数据范围:输入的字符串长度满足

输入描述:

一组字符串。



输出描述:

如果符合要求输出:OK,否则输出NG

示例1

输入

021Abc9000
021Abc9Abc1
021ABC9000
021$bc9000

输出

OK
NG
NG
OK
import re
while True:
    try:
        output = "NG" #初始化NG
        str1 = input()
        if len(str1) > 8: #长度满足
            a=re.search(r'[A-Z]', str1)
            b= re.search(r'[a-z]', str1)
            c = re.search(r'\d', str1)
            d = re.search(r'[^a-z A-Z \d]',str1) #不能用^\w, 因为\w包含下划线
            #r也可用for loop 遍历 str1.count(str1[i:i+3])看是否有3个一样的出现则count>0
            r = re.findall(r'(.{3}).*\1', str1)#在str1 中找到长满足前面为(.{3,}) 后面不远处跟着\1 格式的,不存在则返回空
            #分组(.{3,})	从左到右(捕获内容)并捕获文本到自动命名的组里
            #捕获内容->.	匹配除换行符以外的任意字符
                    #{3,}	内容重复3次或更多次,也就是选择长度大于2的除换行外的字串这道题也可直接{3}因为连续>=3个相同的那=3个肯定也满足
            #	.*\1
                    #.*	经过除换行符以外的任意字符,重复任意次。
                    #\1	后向引用出现分组1中捕获的内容(也就是前面捕获的长度大于2的字串)
            if [a,b,c,d].count(None) <= 1  and r == []: #类别满足至少3种(最多一个None), 并没有相同的返回
                output = "OK"
        print(output)
    except:
        break

#\转义
#| 匹配左右任意一个表达式
#.	匹配除换行符以外的任意字符
#\w	匹配字母或数字或下划线或汉字
#\s	匹配任意的空白符
#\d	匹配数字
#\b	匹配单词的开始或结束
#\W	匹配任意不是字母,数字,下划线,汉字的字符
#\S	匹配任意不是空白符的字符
#\D	匹配任意非数字的字符
#\B	匹配不是单词开头或结束的位置
#^	匹配字符串的开始
#$	匹配字符串的结束
#*	重复零次或更多次
#+	重复一次或更多次
#?	重复零次或一次
#[^x]	匹配除了x以外的任意字符
#[^aeiou]	匹配除了aeiou这几个字母以外的任意字符
#{n}	重复n次
#{n,}	重复n次或更多次
#{n,m}	重复n到m次
#*?	重复任意次,但尽可能少重复
#+?	重复1次或更多次,但尽可能少重复
#??	重复0次或1次,但尽可能少重复
#{n,m}?	重复n到m次,但尽可能少重复
#{n,}?	重复n次以上,但尽可能少重复
#(exp)	匹配exp,并捕获文本到自动命名的组里
#(?<name>exp)	匹配exp,并捕获文本到名称为name的组里,也可以写成(?'name'exp)
#(?:exp)	匹配exp,不捕获匹配的文本,也不给此分组分配组号
#(?=exp)	匹配exp前面的位置
#(?<=exp)	匹配exp后面的位置
#(?!exp)	匹配后面跟的不是exp的位置
#(?<!exp)	匹配前面不是exp的位置
#(?#comment)	不对正则表达式的处理产生任何影响,提供注释让人阅读

编辑于 2021-07-02 17:03:57 回复(1)

""" python3 """

import sys

# 找出所有大于2 (从3起) 的子字符串
def findAllSubStr(str1, subStrLst):
    lenStr = len(str1)
    for i in range(lenStr):
        for j in range(3, lenStr):
            if(i + j < lenStr):
                subStrLst.append(str1[i:(i+j)])

# check 子字符串中是否有重复的
def isDup(lst):
    if (len(lst) > len(set(lst))):
        return True
    else:
        return False

# 字符串中 `数字`, `大写字母`, `小写字母`, `其他字符` 的类型数        
def charTypeCount(str1):
    charTypes = {'num':0, 'lower':0, 'upper':0, 'other':0}
    sum = 0
    for c in str1:
        try:
            if c.isdecimal() or  c.islower() or c.isupper():
                if (0 == charTypes['num']) and (c.isdecimal()):
                    charTypes['num'] = 1
                elif (0 == charTypes['lower']) and (c.islower()):
                    charTypes['lower'] = 1
                elif (0 == charTypes['upper']) and (c.isupper()):
                    charTypes['upper'] = 1
                else:
                    pass
            else:
                if (0 == charTypes['other']) and (c):
                    charTypes['other'] = 1
                else:
                    pass
        except:
            print("fault")
    for value in charTypes.values():
        sum += value
    return sum

if __name__ == "__main__":
    strLst = []
    while True:
        strIn = sys.stdin.readline().strip()
        if (strIn):
            strLst.append(strIn)
        else:
            break
    for strT in strLst:
        if len(strT) < 9:      # 长度大于8, 从 9 开始
            print("NG")
        else:
            subStrLst = []
            findAllSubStr(strT, subStrLst);
            if(isDup(subStrLst)):
                print("NG")
            else:
                if (charTypeCount(strT) > 2):
                    print("OK")
                else:
                    print("NG")
发表于 2021-06-03 23:10:37 回复(0)
import sys
import re

def func(s):
    if len(s) <=8 :
        return 'NG'
    arr = [0, 0, 0, 0]
    for c in s:
        if c.isupper():
            arr[0] = 1
        elif c.islower():
            arr[1] = 1
        elif c.isdigit():
            arr[2] = 1
        else:
            arr[3] = 1
    if sum(arr) < 3:
        return 'NG'
    if re.findall(r'(.{3,}).*\1', s):
        return 'NG'
    return 'OK'

for line in sys.stdin:
    print(func(line.strip()))

发表于 2021-05-04 11:20:28 回复(0)
def judge(s):
    for i in range(len(s)-2):
        for j in range(i+1, len(s)-2):
            if s[i:i+3] == s[j:j+3]:
                return True
    return False
def cal(s):
    if len(s) <= 8:
        print("NG")
        return
    if judge(s):
        print("NG")
        return
    lst = ['1','2','3','4','5','6','7','8','9','0']
    flag1 = 0
    flag2 = 0
    flag3 = 0
    flag4 = 0
    for i in s:
        if i.isupper():
            flag1 = 1
        elif i.islower():
            flag2 = 1
        elif i in lst:
            flag3 = 1
        else:
            flag4 = 1
    total = flag1+flag2+flag3+flag4
    if total > 2:
        print("OK")
        return
    print("NG")
while True:
    try:
        s = input()
        cal(s)
    except:
        break
发表于 2021-04-21 10:28:59 回复(0)
import sys

for line in sys.stdin:
    a = line.split()
    ins = a[0]
    
    if len(ins) <= 8:
        print('NG')
        continue
        
    types = []
    for i in ins:
        if 97 <= ord(i) <= 122:
            if "小写字母" not in types:
                types.append("小写字母")
                continue
        if 65 <= ord(i) <= 90:
            if "大写字母" not in types:
                types.append("大写字母")
                continue
        if 48 <= ord(i) <= 57:
            if "数字" not in types:
                types.append("数字")
                continue
        if 33 <= ord(i) <= 42:
            if "特殊字符" not in types:
                types.append("特殊字符")
                continue
    if len(types) < 3:
        print('NG')
        continue
        
    ans = True
    for i in range(len(ins)-2):
        str1 = ins[i:i+3]
        for j in range(len(ins)-2):
            str2 = ins[j:j+3]
            if str1 == str2 and j != i:
                ans = False
                break
        if not ans:
            break
    if ans:
        print('OK')
    else:
        print('NG')

发表于 2021-04-14 16:54:16 回复(0)
while True:
    try:
        y=1
        a,b,c,d=0,0,0,0
        str1=input()
        if len(str1)<=8:
            y=0
        if y:
            for i in str1:
                if i.isupper():
                    a=1
                elif i.islower():
                    b=1
                elif i.isnumeric():
                    c=1
                else:
                    d=1
            if a+b+c+d<3:
                y=0
        if y:
            for i in range(len(str1)-4):
                    if str1[i:i+3] in str1[i+3:len(str1)]:
                        y=0
        if y:
            print('OK')
        else:
            print('NG')
                
    except:
        break
发表于 2021-03-28 09:34:29 回复(0)
def validate(str):
    error = 0
    chars = {}
    if len(str) <= 8:
        error = 1
    upper = 0
    lower = 0
    numeric = 0
    other = 0
    for x in str:
        if x.isupper() == True:
            upper = 1
        elif x.islower() == True:
            lower = 1
        elif x.isnumeric() == True:
            numeric = 1
        else:
            other = 1
    variety = upper + lower + numeric + other
    if variety < 3:
        error = 2
    i = 0
    for i in range(len(str) - 3):
            if str.count(str[i:i+3]) > 1:
                error = 3
    return error

while True:
    try:
        password = input()
        if validate(password) == 0:
            print('OK')
        elif validate(password) > 0:
            print('NG')
    except EOFError:
        break

发表于 2021-03-27 12:29:48 回复(0)
import sys
import re

test_data = [d.strip() for d in sys.stdin.readlines()]


def check_length(s):
    if len(s) <= 8:
        return False
    else:
        return True
    
    
def check_child_str(s):
    # 长度为3的子串
    for i in range(len(s) - 4):
        sub_str = s[i:i+3]
        if s.count(sub_str) >= 2:
            return False
    else:
        return True


def check_catalogs(s):
    flag = 0
    # A-Z
    if re.search(r"[A-Z]+", s):
        flag += 1
    if re.search(r"[a-z]+", s):
        flag += 1
    if re.search(r"[0-9]+", s):
        flag += 1
    if re.search(r"[^A-Za-z]+", s):
        flag += 1
        
    if flag < 3:
        return False
    else:
        return True


for s in test_data:
    # 长度不足8位
    if check_child_str(s) and check_catalogs(s) and check_length(s):
        print("OK")
    else:
        print("NG")
发表于 2021-03-21 15:03:08 回复(0)
while True:
    try:
        str_in = input()
        isgoodpw = set()
        flag = True
        if len(str_in) > 8:
            for i in str_in:
                if i.isdigit():
                    isgoodpw.add(0)
                elif i.isupper():
                    isgoodpw.add(1)
                elif i.islower():
                    isgoodpw.add(2)
                else:
                    isgoodpw.add(3)

            for j in range(len(str_in) - 3):
                if str_in.count(str_in[j: j + 3]) > 1:
                    flag = False
                    break
                else:
                    pass

            if len(isgoodpw) > 2 and flag == True:
                print("OK")
            else:
                print("NG")
        else:
            print("NG")

    except EOFError:
        break

看了下别人的思路,然后才写出来的。这么简单的题,唉。
发表于 2021-03-03 23:57:45 回复(0)
import re
while True :
    try :
        s = input()
        if len(s) <= 8 :
            print("NG")
            continue
        control = True
        for i in range(len(s)-3):
            for j in range(i+1,len(s)-2):
                if s[i:i+3] == s[j:j+3] :
                    control = False
                    break
        num = 0
        lower = re.compile(r'[a-z]')
        upper = re.compile(r'[A-Z]')
        digital = re.compile(r'\d')
        other = re.compile(r'[^a-zA-Z0-9]')
        if lower.search(s) : num += 1
        if upper.search(s) : num += 1
        if digital.search(s) : num += 1
        if other.search(s) : num += 1
        
        if num >= 3 and control :
            print("OK")
        else : 
            print("NG")
    except:
        break

发表于 2021-02-20 11:55:02 回复(0)
我就想问下这个字符串str="7v0T+6s!(7*)C4RX8*IB85yk+6&~#v6)q$+W3&8-8+"
这个片段为+6不是重复的么
发表于 2021-01-13 17:23:58 回复(1)
import re
import sys


for s in sys.stdin:
    s = s.strip()
    a = re.search(r"(.{3,}).*\1", s)
    b1 = re.search(r"[0-9]", s)
    b2 = re.search(r"[A-Z]", s)
    b3 = re.search(r"[a-z]", s)
    b4 = re.search(r"[^0-9A-Za-z]", s)
    print("OK" if not a and [b1, b2, b3, b4].count(None)<2 and len(s)>8 else "NG")

发表于 2020-12-14 19:54:07 回复(0)
import re
while True:
    try:
        i = input()
        if len(i) <= 8:
            print('NG')
        else:
            low = re.search(r'[a-z]', i)
            up = re.search(r'[A-Z]', i)
            num = re.search(r'[0-9]', i)
            ch = re.search(r'[^0-9A-Za-z]', i)
            if [low, up, num, ch].count(None) > 1:
                print('NG')
            else:
                repeat_substr = re.findall(r'(.{3,}).*?\1', i)
                if repeat_substr:
                    print('NG')
                else:
                    print('OK')
    except:
        break
发表于 2020-09-25 22:17:30 回复(0)
import sys

for s in sys.stdin.readlines():
    s = s.strip('\n')
    if len(s) < 8:
        print('NG')
    else:
        import re
        A = re.findall('[A-Z]',s)
        a = re.findall('[a-z]',s)
        num = re.findall('\d',s)
        oth = re.findall('[^\d a-z A-Z]',s)
        le = list(map(int,[len(A),len(a),len(num),len(oth)]))

        def isre2(s):
            for i in range(3,len(s)+1):
                for j in range(len(s)-2): #索引
                    z = s[j:min(j+i,len(s))] #子串
                    if s.count(z) > 1:
                        return True
            return False

        if le.count(0) > 1:
            print('NG')
        else:
            if isre2(s):
                print('NG')
            else:
                print('OK')
我在自己机子上可以通过测试用例,为什么在线测试总是60%呢???

发表于 2020-09-22 03:29:17 回复(0)
import re
def func(a):
    if len(a)<=8:
        return "NG"
    else:
        for i in range(len(a)-2):
            if a.count(a[i:i+3])>=2:
                return "NG"
        num = re.findall(r'[0-9]', a)
        alp_upper = re.findall(r'[A-Z]', a)
        alp_lower = re.findall(r'[a-z]', a)
        sp = re.findall(r'\W', a)
        if ([num, alp_upper, alp_lower, sp].count([]))>1:
            return "NG"
        else:
            return "OK"
while True:
    try:
        a = input()
        if a:
            print(func(a))
    except:
        break

编辑于 2020-09-02 12:56:11 回复(0)
对于验证输入是否满足某些指定规则,使用正则表达式最为合适,不过得先掌握正则表达式的规则。
首先判断长度小于8,在判别是否含有大小写字母,数字以及其他字符至少三种,比较难的是大于2个的重复字符的判断,此处,本人的判断正则表达式为
r'(.{3,}?).*?\1.*',满足所有规则,即为有效密码。
import sys
import re

passwords = []
for line in sys.stdin:
    if line == '\n':
        break
    passwords.append(line.strip())

for password in passwords:
    if len(password) <= 8:
        print('NG')
    else:
        patterns = [r'[a-z]+?', r'[A-Z]+?', r'\d+?', r'[^a-zA-Z0-9]+?']
        rules = [re.search(pat, password) for pat in patterns]
        rules = list(filter(lambda x: x is not None, rules))
        repeat = re.search(r'(.{3,}?).*?\1.*', password)
        if len(rules) >= 3 and repeat is None:
            print('OK')
        else:
            print('NG')

发表于 2020-08-26 22:51:23 回复(0)
没想到正则匹配子串的方法,用的find和rfind匹配子串
import re
# 判断字符串的组成类型
def getRightType(string):
    lower_case = re.findall(r"[a-z]",string)
    upper_case = re.findall(r"[A-Z]",string)
    digit = re.findall(r"[0-9]",string)
    other_type = re.findall(r"[^A-Za-z0-9]",string)
    not_match_num = [lower_case,upper_case,digit,other_type].count([])
    if not_match_num <= 1:
        return True
    return False

# 判断是否有长度大于2的子串
def sameSubStr(string):
    for i in range(len(string)-3):
        subStr = string[i:i+3]
        pre_index = string.find(subStr)
        last_index = string.rfind(subStr)
        if last_index != pre_index:
            return False
    return True

while True:
    try:
        string = input()
        three_type_bove = getRightType(string)
        same_sub_str = sameSubStr(string)
        if len(string) > 8 and three_type_bove and same_sub_str:
            print("OK")
        else:
            print("NG")
    except:
        break


发表于 2020-08-21 10:34:51 回复(0)
while True:
    try:
        s = str(raw_input())
        NG = False
        if len(s)<=8:
            NG = True
        dicts = {}
        for elem in s:
            if elem.isdigit():
                dicts["digit"] = 1
            elif elem.islower():
                dicts["lower"] = 1
            elif elem.isupper():
                dicts["upper"] = 1
            else:
                dicts["other"] = 1
        if len(list(dicts)) < 3:
            NG = True
        for i in range(len(s)-3):
            for j in range(i+3,len(s)-2):
                if s[i:i+3] == s[j:j+3]:
                    NG = True
        if NG:
            print("NG")
        else:
            print("OK")
    except:
        break
不用正则表达式最原始的做法
发表于 2020-06-11 17:22:36 回复(0)

问题信息

难度:
53条回答 92702浏览

热门推荐

通过挑战的用户

查看代码