题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
http://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
lines = [] while True: try: line = input().strip() lines.append(line) except EOFError: break def Out(total): outStr = '' for i in range(7): outStr += str(total[i]) +' ' print(outStr.strip()) def inGroup(item):#判断数字是否在0~255之间 if len(item)>=2 and item[0]=='0': #以0 开头的非法字符 return False try: item = int(item) if item >=0 and item <=255: return True else: return False except ValueError: return False def getIpType(ip):#判断ip类型 A,B,C,D,E,或错误 items = ip.split('.') if len(items)==4:#子项为4,且首项不为零 for i in range(4): if not inGroup(items[i]):#判断每一项是否为0~255之间 return 5 if int(items[0])>=1 and int(items[0])<=126: return 0 elif int(items[0])>=128 and int(items[0])<=191: return 1 elif int(items[0])>=192 and int(items[0])<=223: return 2 elif int(items[0])>=224 and int(items[0])<=239: return 3 elif int(items[0])>=240 and int(items[0])<=255: return 4 return 5 def isPersonalIp(ip): items = ip.split('.') if int(items[0]) ==10&nbs***bsp;int(items[0])==172 and int(items[1])>=16 and int(items[1])<=31&nbs***bsp;int(items[0])==192 and int(items[1])==168: return True #私有IP地址 return False def isMask(mask):#判断mask是否正确 items = mask.split('.') if len(items)==4:#子项为4,且首项不为零 for i in range(4): if not inGroup(items[i]):#判断每一项是否为0~255之间 return False if int(items[0])==255 and int(items[1])==255 and int(items[2])==255 and int(items[3]) in {0,128,192,224,240,248,252,254}: return True if int(items[0])==255 and int(items[1])==255 and int(items[2]) in {0,128,192,224,240,248,252,254,255} and int(items[3]) == 0: return True if int(items[0])==255 and int(items[1]) in {0,128,192,224,240,248,252,254,255} and int(items[2])==0 and int(items[3]) == 0: return True if int(items[0]) in {128,192,224,240,248,252,254,255} and int(items[1])==0 and int(items[2])==0 and int(items[3]) == 0: return True return False total = [0 for i in range(7)] for line in lines: #判断每一行的ip和mask linelist = line.split('~') if len(linelist) == 2: if linelist[0].split('.')[0]=='0'&nbs***bsp;linelist[0].split('.')[0]=='127': #忽略 continue mask = linelist[1] if not isMask(mask): total[5] += 1 else: ip = linelist[0] index = getIpType(ip) if index>=0: total[index] += 1 if index != 5 and isPersonalIp(ip): #私有ip单独计算 total[6] += 1#私有ip Out(total)