题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
# 1.检测ip是否有效,无效不计入任何类别 # 2.有效ip,检测掩码,掩码非法计入非法类别 # 3.检测ABCDE类别 # 4.检测私人 import re dict_={ 'A':0, 'B':0, 'C':0, 'D':0, 'E':0, 'illegal':0, 'private':0 } def if_ip(text:str): text0 = text.split('~')[0] # 提取ip try: list_ip = [int(i) for i in text0.split('.')] if list_ip[0] in range(1, 256) and list_ip[1] in range(0, 256) and list_ip[2] in range(0, 256) and list_ip[3] in range(0, 256): if list_ip[0] != 127: return True else: return False except: return False def if_mask(text:str): if if_ip(text): text1 = text.split('~')[1] num = ''.join([f'{bin(int(i, 10))[2:]:0>8}' for i in text1.split('.')]) # 1.拆出4位 存储位列表 # 2.用生成器取出 # 3.进制转换位二进制 # 4.右对齐为8位,不足位补0 # 5.合并为字符串 if re.match(r'^[1]+[0]+$', num): # match返回值可以直接进行逻辑运算 return True else: dict_['illegal']+=1 return False else: return None def ip_type(text:str): if if_ip(text) and if_mask(text): text0 = text.split('~')[0] # 提取ip list_ip = [int(i) for i in text0.split('.')] if 1 <= list_ip[0] <= 126: dict_['A']+=1 if list_ip[0] == 10: dict_['private']+=1 return True elif 128 <= list_ip[0] <= 191: dict_['B']+=1 if list_ip[0] == 172 and 16 <= list_ip[1] <= 31: dict_['private']+=1 return True elif 192 <= list_ip[0] <= 223: if list_ip[0] == 192 and list_ip[1] == 168: dict_['private']+=1 dict_['C']+=1 return True elif 224 <= list_ip[0] <= 239: dict_['D']+=1 return True elif 240 <= list_ip[0] <= 255: dict_['E']+=1 return True else: return None while True: try: ip = input() if if_ip(ip): if if_mask(ip): ip_type(ip) except: break for tmp in dict_: print(dict_[tmp], end=' ')