题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
感觉应该是最短的代码了 自己写出来的纪念下
A,B,C,D,E,I,P=0,0,0,0,0,0,0 def ill(s): #判断掩码是否非法 非法返回true 跳出循环 if ('0' not in s) or ('1' not in s): return True for i in range(len(s)): if s[i]=='0': for each in s1[i:]: if each != '0': return True while True: try: s=list(map(str,input().split('~'))) b,a=[],[] s1='' for each in s: b.append(list(map(str,each.split('.')))) if b[0][0]=='0' or b[0][0]=='127': continue if '' in b[0] or '' in b[1]: I+=1 continue for each in s: a.append(list(map(int,each.split('.')))) for i in range(len(a[1])): s1+=bin(a[1][i])[2:].rjust(8,'0') #右对齐补零避免把类似255.255.255.32的掩码判断为合法 if ill(s1): I+=1 continue if [1,0,0,0]<=a[0]<=[126,255,255,255]: A+=1 elif [128,0,0,0]<=a[0]<=[191,255,255,255]: B+=1 elif [192,0,0,0]<=a[0]<=[223,255,255,255]: C+=1 elif [224,0,0,0]<=a[0]<=[239,255,255,255]: D+=1 elif [240,0,0,0]<=a[0]<=[255,255,255,255]: E+=1 if [10,0,0,0]<=a[0]<=[10,255,255,255] or [172,16,0,0]<=a[0]<=[172,3,255,255] or [192,168,0,0]<=a[0]<=[192,168,255,255]: P+=1 except: break print(A,B,C,D,E,I,P)