题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
import sys
nums_of_IP = [0 for _ in range(7)] # 存储不同IP类型的数量
def Mask_ip(address):
lst = address.split('.')
if '' in lst:
return False
adress_ob=''
for ad in lst:
mask_ev=bin(int(ad))[2:].zfill(8)
adress_ob=adress_ob+mask_ev # 去除前缀
if '0' not in adress_ob:
return False
if '1' not in adress_ob:
return False
for index, a in enumerate(adress_ob):
if a == '0':
if '1' in adress_ob[index:]:
return False
else:
return True
return True
def Private_ip(address):
Ip_lst = list(map(int, address.split('.')))
if Ip_lst[0] == 10:
return True
elif Ip_lst[0] == 172:
if Ip_lst[1] >= 16 and Ip_lst[1] <= 31:
return True
elif Ip_lst[0] == 192:
if Ip_lst[1] == 168:
return True
else:
return False
def Avaliabe_address(address):
lst = address.split('.')
if '' not in lst:
Ip_lst=list(map(int,lst))
if Ip_lst[0] < 1 or Ip_lst[0] > 255:
return False
else:
if Ip_lst[1] < 0 or Ip_lst[1] > 255:
return False
else:
if Ip_lst[2] < 0 or Ip_lst[2] > 255:
return False
else:
if Ip_lst[3] < 0 or Ip_lst[3] > 255:
return False
else:
return True
else:
return False
def Leibie(address):
Ip_lst = list(map(int, address.split('.')))
if Ip_lst[0] <= 126:
return 0
elif Ip_lst[0] >= 128 and Ip_lst[0] <= 191:
return 1
elif Ip_lst[0] >= 192 and Ip_lst[0] <= 223:
return 2
elif Ip_lst[0] >= 224 and Ip_lst[0] <= 239:
return 3
elif Ip_lst[0] >= 240 and Ip_lst[0] <= 255:
return 4
while True:
try:
ip_address = input().strip().split('~')
mask = ip_address[1]
ip = ip_address[0]
prefix = int(ip.split('.')[0])
if prefix != 0 and prefix != 127:
if not Avaliabe_address(ip) or not Mask_ip(mask):
nums_of_IP[5] += 1
else:
if Private_ip(ip) and Mask_ip(mask):
nums_of_IP[6] += 1
typeip = Leibie(ip)
if typeip == 0 and Mask_ip(mask):
nums_of_IP[0] += 1
elif typeip == 1 and Mask_ip(mask):
nums_of_IP[1] += 1
elif typeip == 2 and Mask_ip(mask):
nums_of_IP[2] += 1
elif typeip == 3 and Mask_ip(mask):
nums_of_IP[3] += 1
elif typeip == 4 and Mask_ip(mask):
nums_of_IP[4] += 1
except:
lst_final = list(map(str, nums_of_IP))
print(' '.join(lst_final))
break
查看8道真题和解析