题解 | 密码强度检查
密码强度检查
https://www.nowcoder.com/practice/40cc4cfe4a7d45839393fc305fc5609e
# 接收来自命令行输入的数据 def receive_strings(): num = int(input()) # 创建一个字典动态存储输入的字符串 strings_dict = {} # 读取字符串输入 for i in range(num): strings_dict[f"string_{i+1}"] = input("") # 计算输入的字符串的长度 li = [] result = [] for key, value in strings_dict.items(): length = len(value) li.append(length) # 计算输入的字符串包含多少种字符 def count_char_types(value): # 初始化各类计数器 digit = False # 数字 upper = False # 大写字母 lower = False # 小写字母 special = False # 特殊字符 count = 0 for char in value: if char.isdigit(): digit = True elif char.isupper(): upper = True elif char.islower(): lower = True else: if not char.isspace(): special = True # 统计包含的类型数量 if digit: count += 1 if upper: count += 1 if lower: count += 1 if special: count += 1 return count # 对每个字符串调用 count_char_types 函数 for value in strings_dict.values(): char_type_count = count_char_types(value) result.append(char_type_count) # 返回三个变量 return strings_dict, li, result # 判定密码强度 def password_adjust(li, result): # 逐个判断每个密码强度 for i in range(len(li)): length = li[i] char_types = result[i] if length < 8: print("Weak") else: if char_types == 4: print("Strong") elif char_types == 3: print("Medium") else: print("Weak") def main(): strings_dict, li, result = receive_strings() password_adjust(li, result) # 运行主程序 if __name__ == "__main__": main()
用的Python语言,首先就是对输入的多个密码循环的创建变量名,这里用了字典的键值对形式存储strings_dict[f"string_{i+1}"] = input("");列表li用来存储密码的长度,result存储密码包含多少种字符。
最后一步是判定密码强度,这个地方处理不当,很容易循环嵌套,对每个字符串长度和包含字符种类循环判断一次;
使用主函数main直接调用receive_strings()和password_adjust()函数