题解| #HJ18 识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
import sys a = 0 b = 0 c = 0 d = 0 e = 0 error = 0 private = 0 def check_ip(ip: str): ip_list = ip.split(".") for num in ip_list: if not num.isdigit(): return False if len(ip_list) != 4 or "" in ip_list: # ip 的长度为4 且每一位不为空 return False for i in ip_list: if int(i) < 0 or int(i) > 255: # 检查Ip每一个10位的值范围为0~255 return False return True def check_mask(mask: str): if not check_ip(mask): return False if mask == "255.255.255.255\n" or mask == "0.0.0.0\n": return False mask_list = list(map(int, mask.split("."))) mask_bin = "".join([bin(mask)[2:].zfill(8) for mask in mask_list]) # 方法一 # mask_bin = "".join([format(mask, "08b") for mask in mask_list]) # 方法二 return mask_bin.find("0") == mask_bin.rfind("1") + 1 and mask_bin.startswith("1") def check_private_ip(ip: str): # 三类私网 ip_list = ip.split(".") if ip_list[0] == "10": return True if ip_list[0] == "172" and 16 <= int(ip_list[1]) <= 31: return True if ip_list[0] == "192" and ip_list[1] == "168": return True return False try: for line in sys.stdin: ip, mask = line.split("~") mask = mask.strip() first = int(ip.split(".")[0]) continue_flag = False # 计数时忽略 【0.*.*.*】和【127.*.*.*】 if first == 0 or first == 127: continue # 校验IP if not check_ip(ip): error += 1 # print('ip error:', ip) continue_flag = True # 如果有误,就不再检验子网掩码 continue # 校验子网掩码 if not check_mask(mask): # print('mask error:', ip) error += 1 continue # 私有IP if check_private_ip(ip): private += 1 # A类地址 if 1 <= first <= 126: a += 1 # B类地址 elif 128 <= first <= 191: b += 1 # C类地址 elif 192 <= first <= 223: c += 1 # D类地址 elif 224 <= first <= 239: d += 1 # E类地址 elif 240 <= first <= 255: e += 1 except: pass print(a, b, c, d, e, error, private) # 分析: # 同一行的ip和掩码算作一个,所以ip错误并且掩码错误,都记作一个错误。 # 题目中讲的子网掩码并不是按照标准的子网掩码。