# 密码要求: # 1.长度超过8位 # 2.包括大小写字母.数字.其它符号,以上四种至少三种 # 3.不能有长度大于2的包含公共元素的子串重复 (注:其他符号不含空格或换行) # 数据范围:输入的字符串长度满足1≤n≤100 # 输入描述: # 一组字符串。 # 输出描述: # 如果符合要求输出:OK,否则输出NG import re def password_judge(string): if len(string) < 8: # 1.长度超过8位 return "NG" num_list = [0, 0, 0, 0] for s in string: if re.search(r'[0-9]', s): num_list[0] += 1 elif re.search(r'[A-Z]', s): num_list[1] += 1 elif re.search(r'[a-z]', s): num_list[2] += 1 else: num_list[3] += 1 num = 0 for i in num_list: if i > 0: num += 1 if num < 3: # 2.包括大小写字母.数字.其它符号,以上四种至少三种 return "NG" # 3.不能有长度大于2的包含公共元素的子串重复 (注:其他符号不含空格或换行) duplicate_list = [] for i in range(len(string)-3): duplicate_list.append(string[i:(i+3)]) if len(set(duplicate_list)) < len(duplicate_list): return "NG" return 'OK' # ################ 因为篇幅太短,所以顺便附上其他题目 ################ # 编写一个函数,计算字符串中含有的不同字符的个数。字符在 ASCII 码范围内( 0~127 ,包括 0 和 127 ), # 换行表示结束符,不算在字符里。不在范围内的不作统计。多个相同的字符只计算一次 # 例如,对于字符串 abaca 而言,有 a、b、c 三种不同的字符,因此输出 3 。 # 数据范围: 1≤n≤500 # 输入描述: # 输入一行没有空格的字符串。 # 输出描述: # 输出 输入字符串中范围在(0~127,包括0和127)字符的种数。 def diff_count(string): if isinstance(string, str): string = string.replace("\n", "") if len(string) <= 1: return len(string) else: new_string = [string[0]] for i in range(1, len(string)): if string[i] != string[i-1] and string[i] not in new_string and 0 <= ord(string[i]) <= 127: new_string.append(string[i]) print("duplicate word is: ", ''.join(new_string)) return len(new_string) else: return 0 # 输入一个只包含小写英文字母和数字的字符串,按照不同字符统计个数由多到少输出统计结果,如果统计的个数相同,则按照ASCII码由小到大排序输出。 # 数据范围:字符串长度满足 1≤len(str)≤1000 # 输入描述: # 一个只包含小写英文字母和数字的字符串。 # 输出描述: # 一个字符串,为不同字母出现次数的降序表示。若出现次数相同,则按ASCII码的升序输出。 def str_count(string): if len(string) < 2: return string dict1 = dict() for i in range(len(string)): if string[i] in dict1.keys(): dict1[string[i]] += 1 else: dict1.update({string[i]: 1}) v0 = list(dict1.values()) result = "" while len(v0) > 0: max_c = max(v0) list1 = [] for k, v in dict1.items(): if v == max_c: list1.append(k) list1.sort() result = result + "".join(list1) for i in range(len(list1)): v0.remove(max_c) return result # ################ ############## ################ if __name__ == '__main__': print("第一题:") string = "021Abc9000" string2 = "021Abc9Abc1" string3 = "021ABC9000" string4 = "021$bc9000" print(password_judge(string)) print(password_judge(string2)) print(password_judge(string3)) print(password_judge(string4)) print("第二题:") # 统计不同字符个数 str1 = "abbccddeabbdfg" num = diff_count(str1) print("str1 has ", num, "classes") print("第三题:") string = "aaddccedcee" print(str_count(string))
笔试题(九):密码合格性验证及字符串字符统计
于 2023-02-08 22:16:59 首次发布