题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
import sys
def change(temp):
try:
li = temp.split(".")
return int(li[0])*pow(256,3)+int(li[1])*pow(256,2)+int(li[2])*pow(256,1)+int(li[3])
except:
return -1
def check(temp):
temp3 = change(temp)
temp2 = bin(temp3)
temp2 = temp2[2:]
where0 = temp2.find("0")
where1 = temp2.rfind("1")
if where1+1 == where0:
return False
return True
res = [0,0,0,0,0,0,0]
lines = sys.stdin.readlines()
for line in lines:
temp = line.split("~")
start = change(temp[0])
end = change(temp[1])
if start == -1:
res[5] += 1
continue
if start >= change("1.0.0.0") and start <= change("126.255.255.255"):
if check(temp[1]):
res[5]+=1
continue
else:
res[0]+=1
elif start >= change("128.0.0.0") and start <= change("191.255.255.255"):
if check(temp[1]):
res[5]+=1
continue
else:
res[1]+=1
elif start >= change("192.0.0.0") and start <= change("223.255.255.255"):
if check(temp[1]):
res[5]+=1
continue
else:
res[2]+=1
elif start >= change("224.0.0.0") and start <= change("239.255.255.255"):
if check(temp[1]):
res[5]+=1
continue
else:
res[3]+=1
elif start >= change("240.0.0.0") and start <= change("255.255.255.255"):
if check(temp[1]):
res[5]+=1
continue
else:
res[4]+=1
else:
continue
if start >= change("10.0.0.0") and start <= change("10.255.255.255"):
res[6]+=1
if start >= change("176.16.0.0") and start <= change("172.31.255.255"):
res[6]+=1
if start >= change("192.168.0.0") and start <= change("192.168.255.255"):
res[6]+=1
print(*res)
解题顺序很重要 纯暴力

