题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
http://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
import sys ipmasks = [] while True: try: ip,mask = input().strip().split('~') ipmasks.append([ip, mask]) except: # print(sys.exc_info()) break #检查ip是否合法 def checkip(ip): ips = ip.split('.') if len(ips) != 4: return False for i in ips: if not i.isdecimal(): return False return True #检查掩码是否合法 def checkmask(mask): if mask == "0.0.0.0" or mask == "255.255.255.255": return False ms = list(map(int,mask.split('.'))) if len(ms) != 4: return False value = 0 for m in ms: value = m + (value << 8) yu = 0 for i in range(31): if(value == 0): return False #低位是0,高位是1,就是有问题 if yu == 1 and value % 2 == 0: return False yu = value % 2 value >>= 1 return True #用个数组,元素表示各个结果的个数 result = [0,0,0,0,0,0,0] for ipmask in ipmasks: ip = ipmask[0] mask = ipmask[1] if not checkmask(mask): result[5] += 1 continue ips= ip.split('.') if (ips[0] == '0' and len(ips) == 4) or (ips[0] == '127' and len(ips) == 4): continue if not checkip(ip): result[5] += 1 continue ipvalues = ip.split('.') ip1 = int(ipvalues[0]) if ip1 < 127: result[0] += 1 elif ip1 < 192: result[1] += 1 elif ip1 < 224: result[2] += 1 elif ip1 < 240: result[3] += 1 else: result[4] += 1 if ipvalues[1].isdecimal(): ip2 = int(ipvalues[1]) if ip1 == 10 or (ip1 == 172 and 16 <= ip2 <= 31) or (ip1 == 192 and ip2 == 168): result[6] += 1 print(' '.join(map(str,result)))