题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
import sys Dict = {"A": 0, "B": 0, "C": 0, "D": 0, "E": 0, "ERROR": 0, "PRIVATE": 0} def ERROR_ip(ip: str): try: ips = list(map(int, ip.split("."))) for item in ips: if int(item) < 0 or int(item) > 255: return True return False except: return True def ERROR_mask(mask: str): if ERROR_ip(mask): return True masks = list(map(int, mask.split("."))) T = [128, 192, 224, 240, 248, 252, 254] if masks[0] not in T + [255] or masks[3] == 255: return True for i in range(1, 4): if masks[i - 1] in [0] + T: if masks[i] != 0: return True if masks[i - 1] == 255: if masks[i] not in [0] + T + [255]: return True return False def PRIVATE_ip(ip: str): ip0 = int(ip.split(".")[0]) ip1 = int(ip.split(".")[1]) if ip0 == 10: return True if ip0 == 172 and ip1 >= 16 and ip1 <= 16: return True if ip0 == 192 and ip1 == 168: return True return False for line in sys.stdin: a = line.split("~") ip, mask = a[0], a[1].split()[0] ip0 = int(ip.split(".")[0]) if ip0 == 0 or ip0 == 127: continue if not ERROR_ip(ip): if not ERROR_mask(mask): if ip0 >= 1 and ip0 <= 126: Dict["A"] += 1 elif ip0 >= 128 and ip0 <= 191: Dict["B"] += 1 elif ip0 >= 192 and ip0 <= 223: Dict["C"] += 1 elif ip0 >= 224 and ip0 <= 239: Dict["D"] += 1 elif ip0 >= 240 and ip0 <= 255: Dict["E"] += 1 if PRIVATE_ip(ip): Dict["PRIVATE"] += 1 else: Dict["ERROR"] += 1 else: Dict["ERROR"] += 1 for v in Dict.values(): print(v, end=" ")