题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
import sys from collections import Counter def valid_ip(ip): p = ip.split('.') if len(p) != 4: return False for _ in p: try: tmp = int(_) except: return False if not 0 <= tmp <= 255: return False return True def valid_mask(mask): m = mask.split('.') if len(m) != 4: return False mb = '' for _ in m: try: tmp = int(_) except: return False if not 0 <= tmp <= 255: return False bt = bin(tmp)[2:] if tmp != 0 and len(bt) < 8: return False mb += bt lb = list(mb) lb = [int(_) for _ in lb] if sum(lb) in [0, 32]: return False while not lb.pop(): pass return False if 0 in lb else True def get_ip_type(ip): p = ip.split('.') p1 = int(p[0]) if 1 <= p1 <= 126: return 'A' elif 128 <= p1 <= 191: return 'B' elif 192 <= p1 <= 223: return 'C' elif 224 <= p1 <= 239: return 'D' return 'E' def is_private(ip): p = ip.split('.') p = [int(_) for _ in p] if p[0] == 10 or (p[0] == 172 and 16 <= p[1] <= 31) or (p[0] == 192 and p[1] == 168): return True return False ct = Counter() for line in sys.stdin: if line: ip, mask = line.split('~') ips = ip.split('.') if ips[0] in ['0', '127']: continue masks = mask.split('.') if not valid_mask(mask): ct['W'] += 1 continue if valid_ip(ip): ct[get_ip_type(ip)] += 1 if is_private(ip): ct['P'] += 1 else: ct['W'] += 1 print(ct['A'], ct['B'], ct['C'], ct['D'], ct['E'], ct['W'], ct['P'])