题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
http://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
直接上代码
def check_ip_type(ip_ym_str):
"""
:param ip_ym_str: 1.1.1.1255.255.255.0')
:return: A B C D E R P
"""
ip_str, ym_str = ip_ym_str.split('
# 先判断子网掩码
if ym_str.count('.') != 3 or '..' in ym_str:
return 'R'
a, b, c, d = list(map(int, ym_str.split('.')))
all_ym_str = ''
for i in [a, b, c, d]:
i_ym = bin(i).replace('0b', '')
if len(i_ym) < 8:
i_ym = '0' * (8 - len(i_ym)) + i_ym
all_ym_str = all_ym_str + i_ym
if not('10' in all_ym_str and '01' not in all_ym_str):
return 'R'
# ip地址
if ip_str.count('.') != 3 or '..' in ip_str:
return 'R'
a, b, c, d = list(map(int, ip_str.split('.')))
if a in [0, 127]:
return 'X'
if a > 255 or b > 255 or c > 255 or d > 255:
return 'R'
if 1 <= a <= 126:
if a == 10:
return 'AP'
else:
return 'A'
if 128 <= a <= 191:
if a == 172 and (16 <= b <= 31):
return 'BP'
else:
return 'B'
if 192 <= a <= 223:
if a == 192 and b == 168:
return 'CP'
else:
return 'C'
if 224 <= a <= 239:
return 'D'
if 240 <= a <= 255:
return 'E'
ip_list = []
ip_result = ''
while True:
try:
s = input()
if s == '':
break
ip_list.append(s)
except:
break
for ip_str in ip_list:
act = check_ip_type(ip_str)
ip_result = ip_result + act
a = ip_result.count('A')
b = ip_result.count('B')
c = ip_result.count('C')
d = ip_result.count('D')
e = ip_result.count('E')
p = ip_result.count('P')
r = ip_result.count('R')
print('{} {} {} {} {} {} {}'.format(a, b, c, d, e, r, p))