题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
def puip(ip):
if 1<=ip[0]<=126:
res[0]+=1
elif 128<=ip[0]<=191:
res[1]+=1
elif 192<=ip[0]<=223:
res[2]+=1
elif 224<=ip[0]<=239:
res[3]+=1
elif 240<=ip[0]<=255:
res[4]+=1
return
def prip(ip):
if ip[0]==10 or (ip[0]==172 and 16<=ip[1]<=32) or(ip[0]==192 and ip[1]==168):
res[6]+=1
return
def ym(msk):
val = (msk[0]<<24) + (msk[1]<<16) + (msk[2]<<8) +(msk[3])
s = bin(val)[2:]
pos0 = s.find('0') #从左往右找第一次0出现位置
pos1 = s.rfind('1') #从右往左找第一次1出现位置
if pos0!=-1 and pos1!=-1 and pos0-pos1==1:
return True
return False
res = [0,0,0,0,0,0,0]
try:
while True:
ip,msk = input().split('~')
ips = [int(i) for i in filter(None,ip.split('.'))]
msks = [int(i) for i in filter(None,msk.split('.'))]
if ips[0]==0 or ips[0]==127:
continue
if len(ips)<4 or len(msks)<4:
res[5]+=1
continue
if ym(msks) == True:
puip(ips)
prip(ips)
else:
res[5]+=1
except EOFError:
print(' '.join(str(i) for i in res))