题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
http://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
def get_lst(s):
lst = []
for i in s.split('.'):
if i.isdigit():
lst.append(int(i))
return lst
def check_ip(lst):
if len(lst) != 4:
return False
# 检查每段数字是否在0~255之间
for i in lst:
if i not in range(0, 256):
return False
return True
def check_mask(lst):
if len(lst) != 4:
return False
res = ''
for i in lst:
temp = bin(i).replace('0b', '')
res += (8 - len(temp)) * '0' + temp # 不足8位用‘0’补全
if '01' in res or '1' not in res or '0' not in res:
return False
return True
dic = {
'a' : 0, 'b' : 0, 'c' : 0, 'd' : 0, 'e' : 0, 'illegal' : 0, 'private' : 0
}
while True:
try:
ip, mask = input().split('~')
lst_ip, lst_mask = get_lst(ip), get_lst(mask)
# 忽略0和127开头的IP地址
if lst_ip[0] in [0, 127]:
continue
if not check_mask(lst_mask):
dic['illegal'] += 1
continue
if not check_ip(lst_ip):
dic['illegal'] += 1
continue
# 检查是否为私网
if (lst_ip[0] == 10) or (lst_ip[0] == 172 and lst_ip[1] in range(16, 32)) or (lst_ip[0] == 192 and lst_ip[1] == 168):
dic['private'] += 1 # 私网
# 继续检查第一段
if lst_ip[0] in range(1, 127):
dic['a'] += 1
elif lst_ip[0] in range(128, 192):
dic['b'] += 1
elif lst_ip[0] in range(192, 224):
dic['c'] += 1
elif lst_ip[0] in range(224, 240):
dic['d'] += 1
elif lst_ip[0] in range(240, 256):
dic['e'] += 1
except:
break
for i in dic.values():
print(i, end=' ')
print()