题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
#这题主要是对题目的理解,出题描述写的不是很清楚
#首先对于0,127开头的ip都不参加统计
#然后对于掩码错误 或IP错误的地址行进行计数
#最后对剩下的地址行进行分类统计和私有ip地址统计
import sys
A,B,C,D,E,F,G=0,0,0,0,0,0,0
def ill(s):
if "0" not in s or "1" not in s:
return True
else:
for i in range(len(s)):
if s[i]=='0':
s=s[i:]
for i in range(len(s)):
if s[i]=="1":
return True
return False
for line in sys.stdin:
b=[]
a = line.split()[0].split("~")
a[0]=a[0].split(".")
a[1]=a[1].split(".")
b.append(['' if i == '' else int(i) for i in a[0]])
b.append(['' if i == '' else int(i) for i in a[1]])
s=""
if b[0][0] in [0, 127]:
continue
for i in range(len(b[1])):
s=s+bin(b[1][i])[2:].rjust(8,'0')
if ill(s):
F=F+1
continue
if '' in a[0]:
F=F+1
continue
if b[0]<=[126,255,255,255] and b[0]>=[1,0,0,0]:
A=A+1
if b[0] >=[128,0,0,0] and b[0]<=[191,255,255,255]:
B = B+ 1
if b[0]>=[192,0,0,0] and b[0]<=[223,255,255,255]:
C = C+ 1
if b[0]>=[224,0,0,0] and b[0]<=[239,255,255,255]:
D = D + 1
if b[0]>=[240,0,0,0] and b[0]<=[255,255,255,255]:
E = E + 1
if ((b[0]>=[10,0,0,0] and b[0]<=[10,255,255,255])
or (b[0]>=[172,16,0,0] and b[0]<=[172,31,255,255])
or (b[0]>=[192,168,0,0] and b[0]<=[192,168,255,255])):
G=G+1
print(A,B,C,D,E,F,G)
