题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
import sys a = b = c = d = e = wrong = p = 0 for line in sys.stdin: l = line.strip() ip, mask = l.split("~") # 处理IP地址问题 address = ip.split(".") if len(address) != 4: wrong += 1 continue digit_adrress = [] worn_flag =0 for x in address: # 无法转为字符串就报错 try: digit = int(x) if 0<=digit<= 255: digit_adrress.append(digit) else: wrong += 1 worn_flag = 1 break except: wrong += 1 worn_flag = 1 break if worn_flag == 1: continue first_digit = digit_adrress[0] if first_digit in {127, 0}: continue # 【0.*.*.*】和【127.*.*.*】类型地址忽略 masks = mask.split('.') mask_digits = [] worn_flag =0 for x in masks: try: digit = int(x) mask_digits.append(digit) except: wrong += 1 worn_flag = 1 break if worn_flag == 1: continue alls ='' for x in mask_digits: alls += format(x, '08b') one_conut = sum(x =='1' for x in alls) manual_one_count = 0 for x in alls: if x == '1': manual_one_count +=1 else: break if one_conut == 0 or one_conut == 32: wrong += 1 continue if one_conut != manual_one_count: wrong += 1 continue second_digit = digit_adrress[1] if first_digit == 10: p+=1 if first_digit == 172: if 16<=second_digit<=31: p+=1 if first_digit == 192: if second_digit==168: p+=1 if 1<=first_digit<=126: a+=1 if 128<=first_digit<=191: b+=1 if 192<=first_digit<=223: c+=1 if 224<=first_digit<=239: d+=1 if 240<=first_digit<=255: e+=1 print(a,b,c,d,e,wrong,p)
屎山代码